首先,在项目中添加引用,添加该COM组件后会再文件夹中出现一个Interop.Excel.dll的文件,将之前的Microsoft Excel 11.0 Object Library组件删除,添加新的Interop.Excel.dll的引用,然后添加excel的.net组件。
然后,现在开始贴代码,导出excel文件的样式设计、保存、释放资源都存放在一个Share.cs的类文件中,using System.IO;using System.Runtime.InteropServices;using Microsoft.Office.Interop.Excel;#region 设置excel样式并保存到PC ///
然后,设置excel表格格式, /// /// 开始列索引 /// 结束列索引 /// 开始行索引 /// 结束行索引 /// Excel.Application对象 /// 文件保存完整路径 public static Excel.Application TableCss(int ksCell, int jsCell, int ksRow, int jsRow, Excel.Application xls) { //设置报表表格为最适应宽度 // xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Select(); xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Columns.AutoFit(); //xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Columns.Attributes.Add('style', 'vnd.ms-excel.numberformat:@'); // //设置整个报表的标题为跨列居中 // xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].Select(); xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[jsRow, jsCell]].HorizontalAlignment = XlHAlign.xlHAlignCenter; // //绘制边框 //xSt.Range[xls.Cells[rowIndex, 1], xls.Cells[1, rowIndex]].Borders.LineStyle = 1; xls.Range[xls.Cells[jsRow, ksCell], xls.Cells[ksRow, ksCell]].Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThick;//。
然后,设置左边线加粗 ,xls.Range[xls.Cells[ksRow, ksCell], xls.Cells[ksRow, jsCell]].Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThick;//设置上边线加粗 xls.Range[xls.Cells[ksRow, jsCell], xls.Cells[jsRow, jsCell]].Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThick;//设置右边线加粗 xls.Range[xls.Cells[jsRow, ksCell], xls.Cells[jsRow, jsCell]].Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThick;//设置下边线加粗 xls.Visible = false; return xls; } [DllImport('User2.dll', CharSet = CharSet.Auto)] public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int///
然后,页面导出代码,#region 导出excel文件 ///
最后,使用该方法导出Excel文件必须要求服务器上安装有最低office 2003的组件才能正常运行,不过也存在不需要引用的方式的方式输出,比如直接编辑成html格式,还有种一个国外牛人写的dll,可以达到与上面相同的效果导出excel不需要安装office工具。
上述方法为小编整理所得,希望能够帮助到大家。