当前位置: 首页 > news >正文

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

Demo文件下载

  1 None.gif using  System;
  2 None.gif using  System.IO;
  3 None.gif using  System.Data;
  4 None.gif using  System.Reflection;
  5 None.gif using  System.Diagnostics;
  6 None.gif using  cfg  =  System.Configuration;
  7 None.gif // using Excel;
  8 None.gif
  9 None.gif namespace  ExcelHelperTest
 10 ExpandedBlockStart.gifContractedBlock.gif dot.gif {
 11ExpandedSubBlockStart.gifContractedSubBlock.gif    /**//// <summary>
 12InBlock.gif    /// 功能说明:套用模板输出Excel,并对数据进行分页
 13InBlock.gif    /// 作    者:Lingyun_k
 14InBlock.gif    /// 创建日期:2005-7-12
 15ExpandedSubBlockEnd.gif    /// </summary>

 16InBlock.gif    public class ExcelHelper
 17ExpandedSubBlockStart.gifContractedSubBlock.gif    dot.gif{
 18InBlock.gif        protected string templetFile = null;
 19InBlock.gif        protected string outputFile = null;
 20InBlock.gif        protected object missing = Missing.Value;
 21InBlock.gif
 22ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 23InBlock.gif        /// 构造函数,需指定模板文件和输出文件完整路径
 24InBlock.gif        /// </summary>
 25InBlock.gif        /// <param name="templetFilePath">Excel模板文件路径</param>
 26ExpandedSubBlockEnd.gif        /// <param name="outputFilePath">输出Excel文件路径</param>

 27InBlock.gif        public ExcelHelper(string templetFilePath,string outputFilePath)
 28ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 29InBlock.gif            if(templetFilePath == null)
 30InBlock.gif                throw new Exception("Excel模板文件路径不能为空!");
 31InBlock.gif
 32InBlock.gif            if(outputFilePath == null)
 33InBlock.gif                throw new Exception("输出Excel文件路径不能为空!");
 34InBlock.gif
 35InBlock.gif            if(!File.Exists(templetFilePath))
 36InBlock.gif                throw new Exception("指定路径的Excel模板文件不存在!");
 37InBlock.gif
 38InBlock.gif            this.templetFile = templetFilePath;
 39InBlock.gif            this.outputFile = outputFilePath;
 40InBlock.gif
 41ExpandedSubBlockEnd.gif        }

 42InBlock.gif
 43ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 44InBlock.gif        /// 将DataTable数据写入Excel文件(套用模板并分页)
 45InBlock.gif        /// </summary>
 46InBlock.gif        /// <param name="dt">DataTable</param>
 47InBlock.gif        /// <param name="rows">每个WorkSheet写入多少行数据</param>
 48InBlock.gif        /// <param name="top">行索引</param>
 49InBlock.gif        /// <param name="left">列索引</param>
 50ExpandedSubBlockEnd.gif        /// <param name="sheetPrefixName">WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2dot.gif</param>

 51InBlock.gif        public void DataTableToExcel(DataTable dt,int rows,int top,int left,string sheetPrefixName)
 52ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
 53InBlock.gif            int rowCount = dt.Rows.Count;        //源DataTable行数
 54InBlock.gif            int colCount = dt.Columns.Count;    //源DataTable列数
 55InBlock.gif            int sheetCount = this.GetSheetCount(rowCount,rows);    //WorkSheet个数
 56InBlock.gif            DateTime beforeTime;    
 57InBlock.gif            DateTime afterTime;
 58InBlock.gif            
 59InBlock.gif            if(sheetPrefixName == null || sheetPrefixName.Trim() == "")
 60InBlock.gif                sheetPrefixName = "Sheet";
 61InBlock.gif
 62InBlock.gif            //创建一个Application对象并使其可见
 63InBlock.gif            beforeTime = DateTime.Now;
 64InBlock.gif            Excel.Application app = new Excel.ApplicationClass();
 65InBlock.gif            app.Visible = true;
 66InBlock.gif            afterTime = DateTime.Now;
 67InBlock.gif
 68InBlock.gif            //打开模板文件,得到WorkBook对象
 69InBlock.gif            Excel.Workbook workBook = app.Workbooks.Open(templetFile,missing,missing,missing,missing,missing,
 70InBlock.gif                                missing,missing,missing,missing,missing,missing,missing);
 71InBlock.gif
 72InBlock.gif            //得到WorkSheet对象
 73InBlock.gif            Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
 74InBlock.gif
 75InBlock.gif            //复制sheetCount-1个WorkSheet对象
 76InBlock.gif            for(int i=1;i<sheetCount;i++)
 77ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 78InBlock.gif                ((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing,workBook.Worksheets[i]);
 79ExpandedSubBlockEnd.gif            }

 80InBlock.gif
 81ExpandedSubBlockStart.gifContractedSubBlock.gif            将源DataTable数据写入Excel#region 将源DataTable数据写入Excel
 82InBlock.gif            for(int i=1;i<=sheetCount;i++)
 83ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
 84InBlock.gif                int startRow = (i - 1* rows;        //记录起始行索引
 85InBlock.gif                int endRow = i * rows;            //记录结束行索引
 86InBlock.gif
 87InBlock.gif                //若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数
 88InBlock.gif                if(i == sheetCount)
 89InBlock.gif                    endRow = rowCount;
 90InBlock.gif
 91InBlock.gif                //获取要写入数据的WorkSheet对象,并重命名
 92InBlock.gif                Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
 93InBlock.gif                sheet.Name = sheetPrefixName + "-" + i.ToString();
 94InBlock.gif
 95InBlock.gif                //将dt中的数据写入WorkSheet
 96InBlock.gif                for(int j=0;j<endRow-startRow;j++)
 97ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
 98InBlock.gif                    for(int k=0;k<colCount;k++)
 99ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
100InBlock.gif                        sheet.Cells[top + j,left + k] = dt.Rows[startRow + j][k].ToString();
101ExpandedSubBlockEnd.gif                    }

102ExpandedSubBlockEnd.gif                }

103InBlock.gif
104InBlock.gif                //写文本框数据
105InBlock.gif                Excel.TextBox txtAuthor = (Excel.TextBox)sheet.TextBoxes("txtAuthor");
106InBlock.gif                Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes("txtDate");
107InBlock.gif                Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes("txtVersion");
108InBlock.gif
109InBlock.gif                txtAuthor.Text = "KLY.NET的Blog";
110InBlock.gif                txtDate.Text = DateTime.Now.ToShortDateString();
111InBlock.gif                txtVersion.Text = "1.0.0.0";
112ExpandedSubBlockEnd.gif            }

113ExpandedSubBlockEnd.gif            #endregion

114InBlock.gif
115InBlock.gif            //输出Excel文件并退出
116InBlock.gif            try
117ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
118InBlock.gif                workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);
119InBlock.gif                workBook.Close(null,null,null);
120InBlock.gif                app.Workbooks.Close();
121InBlock.gif                app.Application.Quit();
122InBlock.gif                app.Quit();
123InBlock.gif
124InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
125InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
126InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
127InBlock.gif
128InBlock.gif                workSheet=null;
129InBlock.gif                workBook=null;
130InBlock.gif                app=null;
131InBlock.gif
132InBlock.gif                GC.Collect();
133ExpandedSubBlockEnd.gif            }

134InBlock.gif            catch(Exception e)
135ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
136InBlock.gif                throw e;
137ExpandedSubBlockEnd.gif            }

138InBlock.gif            finally
139ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
140InBlock.gif                Process[] myProcesses;
141InBlock.gif                DateTime startTime;
142InBlock.gif                myProcesses = Process.GetProcessesByName("Excel");
143InBlock.gif
144InBlock.gif                //得不到Excel进程ID,暂时只能判断进程启动时间
145InBlock.gif                foreach(Process myProcess in myProcesses)
146ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
147InBlock.gif                    startTime = myProcess.StartTime;
148InBlock.gif
149InBlock.gif                    if(startTime > beforeTime && startTime < afterTime)
150ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
151InBlock.gif                        myProcess.Kill();
152ExpandedSubBlockEnd.gif                    }

153ExpandedSubBlockEnd.gif                }

154ExpandedSubBlockEnd.gif            }

155InBlock.gif            
156ExpandedSubBlockEnd.gif        }

157InBlock.gif
158InBlock.gif        
159ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
160InBlock.gif        /// 获取WorkSheet数量
161InBlock.gif        /// </summary>
162InBlock.gif        /// <param name="rowCount">记录总行数</param>
163ExpandedSubBlockEnd.gif        /// <param name="rows">每WorkSheet行数</param>

164InBlock.gif        private int GetSheetCount(int rowCount,int rows)
165ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
166InBlock.gif            int n = rowCount % rows;        //余数
167InBlock.gif
168InBlock.gif            if(n == 0)
169InBlock.gif                return rowCount / rows;
170InBlock.gif            else
171InBlock.gif                return Convert.ToInt32(rowCount / rows) + 1;
172ExpandedSubBlockEnd.gif        }

173InBlock.gif
174InBlock.gif
175ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
176InBlock.gif        /// 将二维数组数据写入Excel文件(套用模板并分页)
177InBlock.gif        /// </summary>
178InBlock.gif        /// <param name="arr">二维数组</param>
179InBlock.gif        /// <param name="rows">每个WorkSheet写入多少行数据</param>
180InBlock.gif        /// <param name="top">行索引</param>
181InBlock.gif        /// <param name="left">列索引</param>
182ExpandedSubBlockEnd.gif        /// <param name="sheetPrefixName">WorkSheet前缀名,比如:前缀名为“Sheet”,那么WorkSheet名称依次为“Sheet-1,Sheet-2dot.gif</param>

183InBlock.gif        public void ArrayToExcel(string[,] arr,int rows,int top,int left,string sheetPrefixName)
184ExpandedSubBlockStart.gifContractedSubBlock.gif        dot.gif{
185InBlock.gif            int rowCount = arr.GetLength(0);        //二维数组行数(一维长度)
186InBlock.gif            int colCount = arr.GetLength(1);    //二维数据列数(二维长度)
187InBlock.gif            int sheetCount = this.GetSheetCount(rowCount,rows);    //WorkSheet个数
188InBlock.gif            DateTime beforeTime;    
189InBlock.gif            DateTime afterTime;
190InBlock.gif            
191InBlock.gif            if(sheetPrefixName == null || sheetPrefixName.Trim() == "")
192InBlock.gif                sheetPrefixName = "Sheet";
193InBlock.gif
194InBlock.gif            //创建一个Application对象并使其可见
195InBlock.gif            beforeTime = DateTime.Now;
196InBlock.gif            Excel.Application app = new Excel.ApplicationClass();
197InBlock.gif            app.Visible = true;
198InBlock.gif            afterTime = DateTime.Now;
199InBlock.gif
200InBlock.gif            //打开模板文件,得到WorkBook对象
201InBlock.gif            Excel.Workbook workBook = app.Workbooks.Open(templetFile,missing,missing,missing,missing,missing,
202InBlock.gif                missing,missing,missing,missing,missing,missing,missing);
203InBlock.gif
204InBlock.gif            //得到WorkSheet对象
205InBlock.gif            Excel.Worksheet workSheet = (Excel.Worksheet)workBook.Sheets.get_Item(1);
206InBlock.gif
207InBlock.gif            //复制sheetCount-1个WorkSheet对象
208InBlock.gif            for(int i=1;i<sheetCount;i++)
209ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
210InBlock.gif                ((Excel.Worksheet)workBook.Worksheets.get_Item(i)).Copy(missing,workBook.Worksheets[i]);
211ExpandedSubBlockEnd.gif            }

212InBlock.gif
213ExpandedSubBlockStart.gifContractedSubBlock.gif            将二维数组数据写入Excel#region 将二维数组数据写入Excel
214InBlock.gif            for(int i=1;i<=sheetCount;i++)
215ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
216InBlock.gif                int startRow = (i - 1* rows;        //记录起始行索引
217InBlock.gif                int endRow = i * rows;            //记录结束行索引
218InBlock.gif
219InBlock.gif                //若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数
220InBlock.gif                if(i == sheetCount)
221InBlock.gif                    endRow = rowCount;
222InBlock.gif
223InBlock.gif                //获取要写入数据的WorkSheet对象,并重命名
224InBlock.gif                Excel.Worksheet sheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);
225InBlock.gif                sheet.Name = sheetPrefixName + "-" + i.ToString();
226InBlock.gif
227InBlock.gif                //将二维数组中的数据写入WorkSheet
228InBlock.gif                for(int j=0;j<endRow-startRow;j++)
229ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
230InBlock.gif                    for(int k=0;k<colCount;k++)
231ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
232InBlock.gif                        sheet.Cells[top + j,left + k] = arr[startRow + j,k];
233ExpandedSubBlockEnd.gif                    }

234ExpandedSubBlockEnd.gif                }

235InBlock.gif
236InBlock.gif                Excel.TextBox txtAuthor = (Excel.TextBox)sheet.TextBoxes("txtAuthor");
237InBlock.gif                Excel.TextBox txtDate = (Excel.TextBox)sheet.TextBoxes("txtDate");
238InBlock.gif                Excel.TextBox txtVersion = (Excel.TextBox)sheet.TextBoxes("txtVersion");
239InBlock.gif
240InBlock.gif                txtAuthor.Text = "KLY.NET的Blog";
241InBlock.gif                txtDate.Text = DateTime.Now.ToShortDateString();
242InBlock.gif                txtVersion.Text = "1.0.0.0";
243ExpandedSubBlockEnd.gif            }

244ExpandedSubBlockEnd.gif            #endregion

245InBlock.gif
246InBlock.gif            //输出Excel文件并退出
247InBlock.gif            try
248ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
249InBlock.gif                workBook.SaveAs(outputFile,missing,missing,missing,missing,missing,Excel.XlSaveAsAccessMode.xlExclusive,missing,missing,missing,missing);
250InBlock.gif                workBook.Close(null,null,null);
251InBlock.gif                app.Workbooks.Close();
252InBlock.gif                app.Application.Quit();
253InBlock.gif                app.Quit();
254InBlock.gif
255InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(workSheet);
256InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(workBook);
257InBlock.gif                System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
258InBlock.gif
259InBlock.gif                workSheet=null;
260InBlock.gif                workBook=null;
261InBlock.gif                app=null;
262InBlock.gif
263InBlock.gif                GC.Collect();
264ExpandedSubBlockEnd.gif            }

265InBlock.gif            catch(Exception e)
266ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
267InBlock.gif                throw e;
268ExpandedSubBlockEnd.gif            }

269InBlock.gif            finally
270ExpandedSubBlockStart.gifContractedSubBlock.gif            dot.gif{
271InBlock.gif                Process[] myProcesses;
272InBlock.gif                DateTime startTime;
273InBlock.gif                myProcesses = Process.GetProcessesByName("Excel");
274InBlock.gif
275InBlock.gif                //得不到Excel进程ID,暂时只能判断进程启动时间
276InBlock.gif                foreach(Process myProcess in myProcesses)
277ExpandedSubBlockStart.gifContractedSubBlock.gif                dot.gif{
278InBlock.gif                    startTime = myProcess.StartTime;
279InBlock.gif
280InBlock.gif                    if(startTime > beforeTime && startTime < afterTime)
281ExpandedSubBlockStart.gifContractedSubBlock.gif                    dot.gif{
282InBlock.gif                        myProcess.Kill();
283ExpandedSubBlockEnd.gif                    }

284ExpandedSubBlockEnd.gif                }

285ExpandedSubBlockEnd.gif            }

286InBlock.gif            
287ExpandedSubBlockEnd.gif        }

288ExpandedSubBlockEnd.gif    }

289ExpandedBlockEnd.gif}

290 None.gif

相关文章:

  • 【SC】SCOM配置AD集成
  • 去了一趟微软
  • 设计模式的有趣解释-追MM
  • 组策略控制Win7电源选项
  • Nginx基本配置备忘
  • 感觉日子变苦了
  • mysql没有delete操作,那是delete from操作,
  • Mybatis架构
  • 关于使用Lock的疑问。
  • ASP.NET MVC5----基本用法
  • 网络分析的发展
  • Web前端MVC框架
  • jquery笔记之属性选择器 查找以某种条件开头的页面元素
  • 分享:微软提供的一个开源控件treeview 的一小个用法
  • com.panie 项目开发随笔(NoF)_环境搭建(2016.12.29)
  • 【Linux系统编程】快速查找errno错误码信息
  • 【RocksDB】TransactionDB源码分析
  • 【跃迁之路】【699天】程序员高效学习方法论探索系列(实验阶段456-2019.1.19)...
  • Angular2开发踩坑系列-生产环境编译
  • CentOS6 编译安装 redis-3.2.3
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • Just for fun——迅速写完快速排序
  • log4j2输出到kafka
  • Python学习笔记 字符串拼接
  • rabbitmq延迟消息示例
  • 阿里研究院入选中国企业智库系统影响力榜
  • 编写符合Python风格的对象
  • 从PHP迁移至Golang - 基础篇
  • 订阅Forge Viewer所有的事件
  • 对象引论
  • 工作中总结前端开发流程--vue项目
  • 那些年我们用过的显示性能指标
  • ​​​​​​​​​​​​​​Γ函数
  • ​决定德拉瓦州地区版图的关键历史事件
  • ​直流电和交流电有什么区别为什么这个时候又要变成直流电呢?交流转换到直流(整流器)直流变交流(逆变器)​
  • !! 2.对十份论文和报告中的关于OpenCV和Android NDK开发的总结
  • #免费 苹果M系芯片Macbook电脑MacOS使用Bash脚本写入(读写)NTFS硬盘教程
  • #微信小程序:微信小程序常见的配置传旨
  • (3)Dubbo启动时qos-server can not bind localhost22222错误解决
  • (html转换)StringEscapeUtils类的转义与反转义方法
  • (Matalb时序预测)WOA-BP鲸鱼算法优化BP神经网络的多维时序回归预测
  • (pojstep1.1.1)poj 1298(直叙式模拟)
  • (vue)el-checkbox 实现展示区分 label 和 value(展示值与选中获取值需不同)
  • (附源码)计算机毕业设计ssm-Java网名推荐系统
  • (九)信息融合方式简介
  • (免费领源码)Python#MySQL图书馆管理系统071718-计算机毕业设计项目选题推荐
  • (一)Linux+Windows下安装ffmpeg
  • (转)Linux整合apache和tomcat构建Web服务器
  • (转)人的集合论——移山之道
  • .axf 转化 .bin文件 的方法
  • .NET Core6.0 MVC+layui+SqlSugar 简单增删改查
  • .NET 反射的使用
  • .NET建议使用的大小写命名原则
  • .NET精简框架的“无法找到资源程序集”异常释疑
  • @NestedConfigurationProperty 注解用法