[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

相关文章

C# string转unicode字符的实现

《C#string转unicode字符的实现》本文主要介绍了C#string转unicode字符的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录1. 获取字符串中每个字符的 Unicode 值示例代码:输出:2. 将 Unicode 值格式化

Linux使用cut进行文本提取的操作方法

《Linux使用cut进行文本提取的操作方法》Linux中的cut命令是一个命令行实用程序,用于从文件或标准输入中提取文本行的部分,本文给大家介绍了Linux使用cut进行文本提取的操作方法,文中有详... 目录简介基础语法常用选项范围选择示例用法-f:字段选择-d:分隔符-c:字符选择-b:字节选择--c

Rust中的BoxT之堆上的数据与递归类型详解

《Rust中的BoxT之堆上的数据与递归类型详解》本文介绍了Rust中的BoxT类型,包括其在堆与栈之间的内存分配,性能优势,以及如何利用BoxT来实现递归类型和处理大小未知类型,通过BoxT,Rus... 目录1. Box<T> 的基础知识1.1 堆与栈的分工1.2 性能优势2.1 递归类型的问题2.2

Python自动化办公之合并多个Excel

《Python自动化办公之合并多个Excel》在日常的办公自动化工作中,尤其是处理大量数据时,合并多个Excel表格是一个常见且繁琐的任务,下面小编就来为大家介绍一下如何使用Python轻松实现合... 目录为什么选择 python 自动化目标使用 Python 合并多个 Excel 文件安装所需库示例代码

Python使用Pandas对比两列数据取最大值的五种方法

《Python使用Pandas对比两列数据取最大值的五种方法》本文主要介绍使用Pandas对比两列数据取最大值的五种方法,包括使用max方法、apply方法结合lambda函数、函数、clip方法、w... 目录引言一、使用max方法二、使用apply方法结合lambda函数三、使用np.maximum函数

Python调用Orator ORM进行数据库操作

《Python调用OratorORM进行数据库操作》OratorORM是一个功能丰富且灵活的PythonORM库,旨在简化数据库操作,它支持多种数据库并提供了简洁且直观的API,下面我们就... 目录Orator ORM 主要特点安装使用示例总结Orator ORM 是一个功能丰富且灵活的 python O

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

C#中读取XML文件的四种常用方法

《C#中读取XML文件的四种常用方法》Xml是Internet环境中跨平台的,依赖于内容的技术,是当前处理结构化文档信息的有力工具,下面我们就来看看C#中读取XML文件的方法都有哪些吧... 目录XML简介格式C#读取XML文件方法使用XmlDocument使用XmlTextReader/XmlTextWr

python使用fastapi实现多语言国际化的操作指南

《python使用fastapi实现多语言国际化的操作指南》本文介绍了使用Python和FastAPI实现多语言国际化的操作指南,包括多语言架构技术栈、翻译管理、前端本地化、语言切换机制以及常见陷阱和... 目录多语言国际化实现指南项目多语言架构技术栈目录结构翻译工作流1. 翻译数据存储2. 翻译生成脚本

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景