c# Aspose.Cells 通过Excel模板生产excel数据再打印
多的不说,我们先来利用Northwind做两个小demo。先说说Aspose.Cells的模板语法:
- &=DataSource.Field,&=[DataSource].[Field]是对DataTable和几何类型的引用,将会从当前行开始竖直向下生成多行数据。
- &=$data:是对变量或数组的引用。数组存在skip,horizontal等属性,具体参见
- &=&=动态公式计算;{r}当前行,{c}当前列,{-n},{n}当前行或列的偏移量前n或后n。
- &==是动态计算,如excel,if等语句。(if(logic_test,true_value,false_value))
还有其他更为复杂的汇总计算的表达式,这里也不在这节多讲,有兴趣的朋友,可以去官网看看。我们先来个简单的例子,光说,总是不行的,还是要代码实践才能说明一切:
代码如下:
App_Code.SqlDbHelper help = new App_Code.SqlDbHelper();
var s = Aspose.Cells.CellsHelper.GetVersion();
var sql = "select WL_TZ,WL_CL,RPCJH_SL,WL_MC,RPCJH_JHKGRQ,RPCJH_JHID,RPCJH_JHID as RPCJH_JHID1,RPCJH_GXID,U_RPCJH_KH,(select rtrim((cast(GYLX_GXID as char(2)))+\' \'+ltrim(GYLX_GXMC)) from GYLX where GYLX_GYLXID=wo.WO_GYLXID and GYLX_GXID=RPCJH_GXID) as gxmc from RPCJH left join wl on RPCJH_WLID=WL_WLID left join wo on wo.WO_WOID=RPCJH_WOID where RPCJH_JHID=\'JHA1909152\' and RPCJH_BZGXID!=\'888\' ";
var dt = help.ExecuteDataTable(sql);
dt.TableName = "Customers";
Workbook workBook = new Workbook(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\机加作业计划卡.xls");
WorkbookDesigner designer = new WorkbookDesigner(workBook);
//数据源
designer.SetDataSource(dt);
//报表单位
designer.SetDataSource("RPCJH_JHID", dt.Rows[0]["RPCJH_JHID"].ToString().Trim());
designer.SetDataSource("U_RPCJH_KH", dt.Rows[0]["U_RPCJH_KH"].ToString().Trim());
designer.SetDataSource("RPCJH_JHID1", "计划编号:" + dt.Rows[0]["RPCJH_JHID1"].ToString().Trim() + " 领卡人:");
designer.SetDataSource("RPCJH_JHKGRQ", "派工日期:" +Convert.ToDateTime(dt.Rows[0]["RPCJH_JHKGRQ"].ToString().Trim()).ToShortDateString());
designer.SetDataSource("WL_MC", "名称:" + dt.Rows[0]["WL_MC"].ToString().Trim());
designer.SetDataSource("WL_TZ", dt.Rows[0]["WL_TZ"].ToString().Trim());
designer.SetDataSource("WL_CL", dt.Rows[0]["WL_CL"].ToString().Trim());
designer.SetDataSource("RPCJH_SL", dt.Rows[0]["RPCJH_SL"].ToString().Trim());
designer.Process();
workBook.Save(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\2.xls", SaveFormat.Xlsx);
designer = null;
生成的excel如下
打印代码如下:
Workbook workbook = new Workbook(@"E:\KaBoProject\GTDB\GTDB\bin\Debug\2.xls");
//Get the worksheet to be printed
Worksheet worksheet = workbook.Worksheets[0];//获取该Excel文档的第一个工作表
//PageSetup pageSetup = worksheet.PageSetup;
//pageSetup.Orientation = PageOrientationType.Landscape;
//pageSetup.LeftMargin = 0;
//pageSetup.RightMargin = 0.1;
//pageSetup.BottomMargin = 0.3;
//pageSetup.PrintArea = "A2:J29";
//Apply different Image / Print options.
Aspose.Cells.Rendering.ImageOrPrintOptions options = new Aspose.Cells.Rendering.ImageOrPrintOptions();
//Set the Printing page property
//options.PrintingPage = PrintingPageType.IgnoreStyle;
//Render the worksheet
SheetRender sr = new SheetRender(worksheet, options);
System.Drawing.Printing.PrinterSettings printSettings = new System.Drawing.Printing.PrinterSettings();
string strPrinterName = printSettings.PrinterName;
//send to printer
//System.Drawing.Image map = sr.ToImage(0);
sr.ToPrinter(strPrinterName);