北京 企业建网站,php mysql网站开发项目式教程,互联网广告价格,站长交易网目录
功能需求
范例运行环境
Excel DCOM 配置
设计实现
组件库引入
编辑
方法设计
生成二维数据数组
核心方法实现
调用示例
总结 功能需求
将数据库查询出来的数据导出并生成 Excel 文件#xff0c;是项目中经常使用的一项功能。本文将介绍通过数据集生成二维…目录
功能需求
范例运行环境
Excel DCOM 配置
设计实现
组件库引入
编辑
方法设计
生成二维数据数组
核心方法实现
调用示例
总结 功能需求
将数据库查询出来的数据导出并生成 Excel 文件是项目中经常使用的一项功能。本文将介绍通过数据集生成二维数据数组并导出到 Excel。
主要实现如下功能
1、根据规则设计EXCEL数据导出模板
2、查询数据并生成 object[,] 二维数据数组
3、将二维数据数组其它要输出的数据导出写入到模板 Excel 文件 范例运行环境
操作系统 Windows Server 2019 DataCenter
操作系统上安装 Office Excel 2016
.net版本 .netFramework4.7.2 或以上
开发工具VS2019 C#
Excel DCOM 配置
请参考我的文章《C# 读取Word表格到DataSet》有对Office DCOM详细配置介绍这里不再赘述Excel的对应配置名称如下图所示
设计实现
组件库引入
方法设计
设计 expExcel 方法实现数据的导出方法返回生成的全文件路径信息。其调用参数据详细说明见下表
序号参数名类型说明1_filenamestringExcel 模板文件的全路径信息2dataobjobject[,]生成的二维数据数组3ActiveSheetIdint指定要导出的活动的SHEETID序号从1开始4StartRowIdint指定数据导出的开始行ID序号从1开始5StartColIdint指定数据导出的开始列ID序号从1开始6_replsstring[,] 在EXCEL模板文件里的查找且替换数组维度1为 key 维度2 为 value 系统会根据提供的数组key在模板文件进行查找并替换对应的 value 值例如 string[,] _replsnew string[1,2]; _repls[0,0]模板标题 key ; _repls[0,1]实际输出的标题值 value; 7drawtypeint 该值包括0和1。 0:从原始指定起始位置覆盖粘贴数据 1从原始指定起始位置插入粘贴数据 8AllDataAsStringbool默认为 false是否将所有数据以文本的形式进行输出9DynamicColsbool默认为false是否按照二维数据数组动态输出行与列10DynamicColCfgArrayList 一个对各列进行配置的参数每个项至少为两个object一个为列名一个为列宽第三个为数据格式如文本、数值等例如 ArrayList cfg new ArrayList(); string _cname 列名1; string _width -1; //-1 表示自动适应列宽 cfg.Add(new object[] { _cname, _width }); 11StartAddressstring对 StartRowId 参数和 StartColId 参数
生成二维数据数组
如何生成二维数据数组请参阅我的文章《C# 读取二维数组集合输出到Word预设表格》中的DataSet转二维数组 章节部分。
核心方法实现
代码如下 public string expExcel(string _filename,object[,] dataobj,int ActiveSheetId,int StartRowId,int StartColId,string[,] _repls,int drawtype,bool AllDataAsString,bool DynamicCols,ArrayList DynamicColCfg,string StartAddress){string AsString(AllDataAsString?:);string _file,_pathPath.GetDirectoryName(_filename)\\tempbfile\\,_ext;if(!Directory.Exists(_path)){Directory.CreateDirectory(_path);}_filePath.GetFileNameWithoutExtension(_filename);_extPath.GetExtension(_filename);string _lastfile_pathSystem.Guid.NewGuid()_ext;File.Copy(_filename,_lastfile,true);if(!File.Exists(_lastfile)){return ;}//取得Word文件保存路径object filename_lastfile;//创建一个名为ExcelApp的组件对象DateTime beforetimeDateTime.Now;Excel.Application excelnew Excel.Application();excel.DisplayAlertsfalse;excel.AskToUpdateLinksfalse;excel.Visibletrue;DateTime aftertimeDateTime.Now;Excel.Workbook xbexcel.Workbooks.Add(_lastfile);Worksheet worksheet (Worksheet) excel.Worksheets[ActiveSheetId];sheetCountexcel.Sheets.Count;worksheet.Activate();if(_repls!null){for(int i0;i_repls.GetLength(0);i){worksheet.Cells.Replace(_repls[i,0],_repls[i,1],Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing); }}Excel.Range _range;Excel.Range srange;if(StartAddress!){Excel.Range _range_sworksheet.Range[StartAddress,StartAddress];StartRowId_range_s.Row;StartColId_range_s.Column;}int arraywidthdataobj.GetLength(1);int arrayheightdataobj.GetLength(0);ArrayList ex_x new ArrayList();ArrayList ex_y new ArrayList();ArrayList ex_value new ArrayList();object _fvalue;int _maxlen910; for(int j0;jarrayheight;j){for(int k0;karraywidth;k){_fvaluedataobj[j,k];// field valueif(_fvaluenull){continue;}if(_fvalue.GetType().ToString()System.String){if(((string)_fvalue).Length_maxlen){ex_x.Add(jStartRowId);ex_y.Add(kStartColId);ex_value.Add(_fvalue);_fvalue;}// end maxlen }dataobj[j,k](_fvalue.ToString().IndexOf()0?:AsString)_fvalue;}//end columns}// end rows if(DynamicColstrue){srangeexcel.Range[excel.Cells[StartRowId,StartColId],excel.Cells[StartRowId,StartColId]];for(int i1;iarraywidth;i){_rangeexcel.Range[excel.Cells[StartRowId,StartColIdi],excel.Cells[StartRowId,StartColIdi]];copyRangeStyle(srange,_range);}}object _copyheightexcel.Range[excel.Cells[StartRowId,StartColId],excel.Cells[StartRowId,StartColIdarraywidth-1]].RowHeight;if(drawtype1) //取startrow的格式{_rangeexcel.Range[excel.Cells[StartRowId1,StartColId],excel.Cells[StartRowIdarrayheight-1,StartColId]];if(arrayheight1){_range.EntireRow.Insert(Excel.XlInsertShiftDirection.xlShiftDown,Type.Missing);}for(int i0;iarraywidth;i){srangeexcel.Range[excel.Cells[StartRowId,StartColIdi],excel.Cells[StartRowId,StartColIdi]];_rangeexcel.Range[excel.Cells[StartRowId1,StartColIdi],excel.Cells[StartRowIdarrayheight-1,StartColIdi]];copyRangeStyle(srange,_range);}_rangeexcel.Range[excel.Cells[StartRowId1,StartColId],excel.Cells[StartRowIdarrayheight-1,StartColIdarraywidth-1]];_range.RowHeight_copyheight;}_rangeexcel.Range[excel.Cells[StartRowId,StartColId],excel.Cells[StartRowIdarrayheight-1,StartColIdarraywidth-1]];_range.get_Resize(arrayheight,arraywidth);_range.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault,dataobj);for(int j0;jex_value.Count;j){excel.Cells[ex_x[j],ex_y[j]]ex_value[j].ToString();}if(DynamicColstrue){if(DynamicColCfg!null){for(int j0;jDynamicColCfg.Count;j){_rangeexcel.Range[excel.Cells[StartRowId,StartColIdj],excel.Cells[StartRowId,StartColIdj]];object[] cfg(object[])DynamicColCfg[j];string _titlecfg[0].ToString();_range.Value2_title;_rangeexcel.Range[excel.Cells[StartRowId,StartColIdj],excel.Cells[65536,StartColIdj]];if(cfg.Length1){int _widthint.Parse(cfg[1].ToString());if(_width!-1){_range.ColumnWidth_width;}else{_range.ColumnWidth 255;_range.Columns.AutoFit();}}if(cfg.Length2){_range.NumberFormatLocalcfg[2].ToString();}//NumberFormatlocal }}}if (WritePassword ! ){xb.WritePassword WritePassword;}if (ProtectPassword ! ){worksheet.Protect(ProtectPassword);xb.Protect(ProtectPassword,true,true);}worksheet.SaveAs(_lastfile, Missing.Value,WritePassword?(object)Missing.Value:(object)WritePassword, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);xb.Close(null,null,null);excel.Workbooks.Close();int pid0;IntPtr a new IntPtr(excel.Parent.Hwnd);UInt32[] processId new UInt32[1];GetWindowThreadProcessId((IntPtr)excel.Hwnd,processId);excel.Quit();if(worksheet ! null){System.Runtime.InteropServices.Marshal.ReleaseComObject(worksheet);worksheet null;}if(xb ! null){System.Runtime.InteropServices.Marshal.ReleaseComObject(xb);xb null;}if(excel ! null){System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);excel null;}GC.Collect();KillProcessByStartTime(EXCEL,beforetime,aftertime);return _lastfile;}public string KillProcessByStartTime(string processName,DateTime beforetime,DateTime aftertime){Process[] ps Process.GetProcesses();foreach (Process p in ps) {if(p.ProcessName.ToUpper()!processName) continue;if(p.StartTime beforetime p.StartTime aftertime){try{p.Kill();}catch(Exception e){return e.Message;}}} return ;} 调用示例
我们设计Web应用中的输出模板Request.PhysicalApplicationPath \\bfile\\excel\\模板.xlsx如下图 如图 %system.excel.title.dyna.by.craneoffice% 表示要替换的标题 key 下面的二维表格表示预设好的输出列下面的行即为数据输出行在这里我们预设要从第1列第5行输出数据。以下是调用的示例代码 object[,] rv DataSetToOject(); //这个是初始化二维数据数组的string[,] _repls new string[1, 2];_repls[0, 0] %system.excel.title.dyna.by.craneoffice%;_repls[0, 1] 考察对象家庭成员及主要社会关系人基本情况;string ModuleFile Request.PhysicalApplicationPath \\bfile\\excel\\模板.xlsx;string _lastfile er.Jree(ModuleFile, rv, 1, 5, 1, _repls, 1, true, false, null);string _url /bfile/excel/tempbfile/ Path.GetFileName(_lastfile); _lastfile 为最终生成的 excel 数据导出文件全路径地址_url 为转化的可下载URL地址。 总结
为保持兼容性本方法支持旧版本的Word97-2003格式如需要突破65536行限制我们可以根据实际需要进行设计调整。
本方法支持数据输出行样式的持续复制即我们可以设置单行样式如字体大小、颜色、边框等方法会根据数据行数循环复制样式进行行输出 。
我们在此仅根据实际项目需要讲述了一些导出数据到Excel的参数需求这里仅作参考欢迎大家评论指教