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

C# Demo文件下载
博客提供C#相关Demo文件下载,涉及C#运行时(runtime)相关内容。

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值