海海日记-冯海滨博客

您现在的位置是:首页 > C# > 正文

C#

Aspose.Cells 插件使用 For C#

happyfhb2018-10-13C#3129

 

最近的项目使用了很多的Excel 作为导出的数据报告,使用到 Aspose.Cells 插件,就顺便整理一下。

一:新建解决方案,目录如下

332282-20171018114234756-1793316766.png

 

 目录说明:

    Program.cs - 入口类

    ExcelGenerator.cs - Aspose.Cells 操作类

    Aspose.Cell.dll - 基础dll【文件见文章底部源代码内】

    License.lic - Aspose.Cells 破解证书【文件见文章底部源代码内】

            ps:由于 Aspose.Cells 插件 是收费插件,需要在使用插件前,设置一下许可证,否则在生成的Excel 中 会出现一个名叫 Evaluation Warning 的 Sheet.如图所示:

是.png


二:Aspose.Cells 操作

 2.1 引入 Aspose.Cell.dll 

2.2 设置 Aspose.Cell.dll 证书 License.lic

    2.2.1 设置证书。我一般都写在生成Excel类的构造函数中了。文件路径要和证书的位置保持一致

1212.png


Excel.License l = new Excel.License();
l.SetLicense("Aid/License.lic");


2.2.2 修改证书属性。在解决方案中,右击 License.lic 选择属性,修改 Copy to Ouput Directory 属性为 Copy always

332282-20171018114234756-1793316766.png

 2.3 打开现有Execl 模板

//模板文件路径string Template_File_Path = @".\Template\Template.xlsx";//  打开 Excel 模板Workbook CurrentWorkbook = File.Exists(Template_File_Path) ? new Workbook(Template_File_Path) : new Workbook();//  打开第一个sheetWorksheet DetailSheet = CurrentWorkbook.Worksheets[0];

  2.4 写入数据

    2.4.1 填写数据到指定单元格
 // 比如要在 A1 位置写入 Demo这个值Cell itemCell = DetailSheet.Cells["A1"];

itemCell.PutValue("Demo");
    2.4.2 把DataTable写入到Excel
//  获取 Table 数据DataTable dt = GetData();            
//  写入数据的起始位置string cell_start_region = "C1";//  获得开始位置的行号                    int startRow = DetailSheet.Cells[cell_start_region].Row;//  获得开始位置的列号  int startColumn = DetailSheet.Cells[cell_start_region].Column;  

//  写入Excel。参数说明,直接查阅文章底部文档链接DetailSheet.Cells.ImportDataTable(dt, false, startRow, startColumn, true, true);

  2.5 保存Excel

//  设置执行公式计算 - 如果代码中用到公式,需要设置计算公式,导出的报表中,公式才会自动计算CurrentWorkbook.CalculateFormula(true);//  生成的文件名称string ReportFileName = string.Format("Excel_{0}.xlsx", DateTime.Now.ToString("yyyy-MM-dd"));//  保存文件CurrentWorkbook.Save(@".\Excel\" + ReportFileName, SaveFormat.Xlsx);


三:参考资料以及源码

  3.1 参考资料

 https://pan.baidu.com/s/1c2jf8Hi

   3.2 源代码。文中用到的证书和dll 都可以在源码中找到

  https://pan.baidu.com/s/1c2tUElU

  

平淡中储蓄成长

发表评论

评论列表

  • 这篇文章还没有收到评论,赶紧来抢沙发吧~