[NET][C#]操作Excel,套用模板并对数据进行分页

2024-03-08 15:18

本文主要是介绍[NET][C#]操作Excel,套用模板并对数据进行分页,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

[NET][C#]操作Excel,套用模板并对数据进行分页
using System;
using System.IO;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using cfg = System.Configuration;
using Excel;
namespace ExcelHelperTest
{
/**/ ///   <summary> 
/// 功能说明:套用模板输出Excel,并对数据进行分页
/// 作    者:Lingyun_k
/// 创建日期:2005-7-12
///   </summary> 
public   class ExcelHelper
{
protected   string templetFile =   null ;
protected   string outputFile =   null ;
protected   object missing = Missing.Value;
/**/ ///   <summary> 
/// 构造函数,需指定模板文件和输出文件完整路径
///   </summary> 
///   <param name="templetFilePath"> Excel模板文件路径 </param> 
///   <param name="outputFilePath"> 输出Excel文件路径 </param> 
public ExcelHelper( string templetFilePath, string outputFilePath)
{
if (templetFilePath ==   null )
throw   new Exception( " Excel模板文件路径不能为空! " );
if (outputFilePath ==   null )
throw   new Exception( " 输出Excel文件路径不能为空! " );
if ( ! File.Exists(templetFilePath))
throw   new Exception( " 指定路径的Excel模板文件不存在! " );
this .templetFile = templetFilePath;
this .outputFile = outputFilePath;
}
/**/ ///   <summary> 
/// 将DataTable数据写入Excel文件(套用模板并分页)
///   </summary> 
///   <param name="dt"> DataTable </param> 
///   <param name="rows"> 每个WorkSheet写入多少行数据 </param> 
///   <param name="top"> 行索引 </param> 
///   <param name="left"> 列索引 </param> 
///   <param name="sheetPrefixName"> WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2” </param> 
public   void DataTableToExcel(DataTable dt, int rows, int top, int left, string sheetPrefixName)
{
int rowCount = dt.Rows.Count;         // 源DataTable行数 
int colCount = dt.Columns.Count;     // 源DataTable列数 
int sheetCount =   this .GetSheetCount(rowCount,rows);     // WorkSheet个数 
DateTime beforeTime;    
DateTime afterTime;
if (sheetPrefixName ==   null   || sheetPrefixName.Trim() ==   "" )
sheetPrefixName =   " Sheet " ;
// 创建一个Application对象并使其可见 
beforeTime = DateTime.Now;
Excel.Application app =   new Excel.ApplicationClass();
app.Visible =   true ;
afterTime = DateTime.Now;
// 打开模板文件,得到WorkBook对象 
Excel.Workbook workBook = app.Workbooks.Open(templetFile,missing,missing,missing,missing,missing,
missing,missing,missing,missing,missing,missing,missing);
// 得到WorkSheet对象 
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item( 1 );
// 复制sheetCount-1个WorkSheet对象 
for ( int i = 1 ;i < sheetCount;i ++ )
{
((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing,workBook.Worksheets[i]);
}
将源DataTable数据写入Excel #region 将源DataTable数据写入Excel 
for ( int i = 1 ;i <= sheetCount;i ++ )
{
int startRow = (i -   1 ) * rows;         // 记录起始行索引 
int endRow = i * rows;             // 记录结束行索引
// 若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数 
if (i == sheetCount)
endRow = rowCount;
// 获取要写入数据的WorkSheet对象,并重命名 
Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
sheet.Name = sheetPrefixName +   " - "   + i.ToString();
// 将dt中的数据写入WorkSheet 
for ( int j = 0 ;j < endRow - startRow;j ++ )
{
for ( int k = 0 ;k < colCount;k ++ )
{
sheet.Cells[top + j,left + k] = dt.Rows[startRow + j][k].ToString();
} 
}
// 写文本框数据 
Excel.TextBox txtAuthor = (Excel.TextBox)sheet.TextBoxes( " txtAuthor " );
Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes( " txtDate " );
Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes( " txtVersion " );
txtAuthor.Text =   " KLY.NET的Blog " ;
txtDate.Text = DateTime.Now.ToShortDateString();
txtVersion.Text =   " 1.0.0.0 " ;
} 
#endregion
// 输出Excel文件并退出 
try 
{
workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);
workBook.Close( null , null , null );
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
workSheet = null ;
workBook = null ;
app = null ;
GC.Collect();
} 
catch (Exception e)
{
throw e;
} 
finally 
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName( " Excel " );
// 得不到Excel进程ID,暂时只能判断进程启动时间 
foreach (Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
} 
} 
} 
}
/**/ ///   <summary> 
/// 获取WorkSheet数量
///   </summary> 
///   <param name="rowCount"> 记录总行数 </param> 
///   <param name="rows"> 每WorkSheet行数 </param> 
private   int GetSheetCount( int rowCount, int rows)
{
int n = rowCount % rows;         // 余数
if (n ==   0 )
return rowCount / rows;
else 
return Convert.ToInt32(rowCount / rows) +   1 ;
}
/**/ ///   <summary> 
/// 将二维数组数据写入Excel文件(套用模板并分页)
///   </summary> 
///   <param name="arr"> 二维数组 </param> 
///   <param name="rows"> 每个WorkSheet写入多少行数据 </param> 
///   <param name="top"> 行索引 </param> 
///   <param name="left"> 列索引 </param> 
///   <param name="sheetPrefixName"> WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2” </param> 
public   void ArrayToExcel( string [,] arr, int rows, int top, int left, string sheetPrefixName)
{
int rowCount = arr.GetLength( 0 );         // 二维数组行数(一维长度) 
int colCount = arr.GetLength( 1 );     // 二维数据列数(二维长度) 
int sheetCount =   this .GetSheetCount(rowCount,rows);     // WorkSheet个数 
DateTime beforeTime;    
DateTime afterTime;
if (sheetPrefixName ==   null   || sheetPrefixName.Trim() ==   "" )
sheetPrefixName =   " Sheet " ;
// 创建一个Application对象并使其可见 
beforeTime = DateTime.Now;
Excel.Application app =   new Excel.ApplicationClass();
app.Visible =   true ;
afterTime = DateTime.Now;
// 打开模板文件,得到WorkBook对象 
Excel.Workbook workBook = app.Workbooks.Open(templetFile,missing,missing,missing,missing,missing,
missing,missing,missing,missing,missing,missing,missing);
// 得到WorkSheet对象 
Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item( 1 );
// 复制sheetCount-1个WorkSheet对象 
for ( int i = 1 ;i < sheetCount;i ++ )
{
((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing,workBook.Worksheets[i]);
}
将二维数组数据写入Excel #region 将二维数组数据写入Excel 
for ( int i = 1 ;i <= sheetCount;i ++ )
{
int startRow = (i -   1 ) * rows;         // 记录起始行索引 
int endRow = i * rows;             // 记录结束行索引
// 若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数 
if (i == sheetCount)
endRow = rowCount;
// 获取要写入数据的WorkSheet对象,并重命名 
Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
sheet.Name = sheetPrefixName +   " - "   + i.ToString();
// 将二维数组中的数据写入WorkSheet 
for ( int j = 0 ;j < endRow - startRow;j ++ )
{
for ( int k = 0 ;k < colCount;k ++ )
{
sheet.Cells[top + j,left + k] = arr[startRow + j,k];
} 
}
Excel.TextBox txtAuthor = (Excel.TextBox)sheet.TextBoxes( " txtAuthor " );
Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes( " txtDate " );
Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes( " txtVersion " );
txtAuthor.Text =   " KLY.NET的Blog " ;
txtDate.Text = DateTime.Now.ToShortDateString();
txtVersion.Text =   " 1.0.0.0 " ;
} 
#endregion
// 输出Excel文件并退出 
try 
{
workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);
workBook.Close( null , null , null );
app.Workbooks.Close();
app.Application.Quit();
app.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
workSheet = null ;
workBook = null ;
app = null ;
GC.Collect();
} 
catch (Exception e)
{
throw e;
} 
finally 
{
Process[] myProcesses;
DateTime startTime;
myProcesses = Process.GetProcessesByName( " Excel " );
// 得不到Excel进程ID,暂时只能判断进程启动时间 
foreach (Process myProcess in myProcesses)
{
startTime = myProcess.StartTime;
if (startTime > beforeTime && startTime < afterTime)
{
myProcess.Kill();
} 
} 
} 
} 
} 
}

这篇关于[NET][C#]操作Excel,套用模板并对数据进行分页的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/787519

相关文章

SpringBoot+EasyPOI轻松实现Excel和Word导出PDF

《SpringBoot+EasyPOI轻松实现Excel和Word导出PDF》在企业级开发中,将Excel和Word文档导出为PDF是常见需求,本文将结合​​EasyPOI和​​Aspose系列工具实... 目录一、环境准备与依赖配置1.1 方案选型1.2 依赖配置(商业库方案)二、Excel 导出 PDF

如何使用Lombok进行spring 注入

《如何使用Lombok进行spring注入》本文介绍如何用Lombok简化Spring注入,推荐优先使用setter注入,通过注解自动生成getter/setter及构造器,减少冗余代码,提升开发效... Lombok为了开发环境简化代码,好处不用多说。spring 注入方式为2种,构造器注入和setter

MySQL进行数据库审计的详细步骤和示例代码

《MySQL进行数据库审计的详细步骤和示例代码》数据库审计通过触发器、内置功能及第三方工具记录和监控数据库活动,确保安全、完整与合规,Java代码实现自动化日志记录,整合分析系统提升监控效率,本文给大... 目录一、数据库审计的基本概念二、使用触发器进行数据库审计1. 创建审计表2. 创建触发器三、Java

Ubuntu 24.04启用root图形登录的操作流程

《Ubuntu24.04启用root图形登录的操作流程》Ubuntu默认禁用root账户的图形与SSH登录,这是为了安全,但在某些场景你可能需要直接用root登录GNOME桌面,本文以Ubuntu2... 目录一、前言二、准备工作三、设置 root 密码四、启用图形界面 root 登录1. 修改 GDM 配

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

MySQL深分页进行性能优化的常见方法

《MySQL深分页进行性能优化的常见方法》在Web应用中,分页查询是数据库操作中的常见需求,然而,在面对大型数据集时,深分页(deeppagination)却成为了性能优化的一个挑战,在本文中,我们将... 目录引言:深分页,真的只是“翻页慢”那么简单吗?一、背景介绍二、深分页的性能问题三、业务场景分析四、

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

C#连接SQL server数据库命令的基本步骤

《C#连接SQLserver数据库命令的基本步骤》文章讲解了连接SQLServer数据库的步骤,包括引入命名空间、构建连接字符串、使用SqlConnection和SqlCommand执行SQL操作,... 目录建议配合使用:如何下载和安装SQL server数据库-CSDN博客1. 引入必要的命名空间2.

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与