首页 > 编程语言 >使用Aspose.Cell控件实现Excel高难度报表的生成(二)

使用Aspose.Cell控件实现Excel高难度报表的生成(二)

时间:2023-10-04 09:00:11浏览次数:37  
标签:控件 designer string rowIndex Cells Excel Cell fileToSave row

继续在上篇《使用Aspose.Cell控件实现Excel高难度报表的生成(一)》随笔基础上,研究探讨基于模板的Aspose.cell报表实现,其中提到了下面两种报表的界面,如下所示:

 或者这样的报表格式

  


首先来分析第一种报表,这个其实还是比较固定的二维表,我们只要绑定相关的信息即可,设计模板如下所示:

 
实际生成的报表如下所示:

 

实现的代码其实不复杂,如下所示:

         private DataTable GetTable(string sql)

复制代码         {
            Database db = DatabaseFactory.CreateDatabase();
            DbCommand command = db.GetSqlStringCommand(sql);
            return db.ExecuteDataSet(command).Tables[0];
        }
        private void btnAllMonthReport_Click(object sender, EventArgs e)
        {
            string sql = @"Select [LastCount] as LC, [LastMoney] as LM, [CurrentInCount] as CIC, [CurrentInMoney] as CIM, 
                           [CurrentOutCount] as COC, [CurrentOutMoney] as COM, [CurrentCount] as CC, [CurrentMoney] as CM, 
                           YearMonth,ItemName 
                           from TB_ReportMonthCheckOut ";
            DataTable dtBigType = GetTable(sql + " where ReportType =3");
            dtBigType.TableName = "BigType";
            if (dtBigType.Rows.Count == 0)
                return;

            DataTable dtItemType = GetTable(sql + " where ReportType =3");
            dtItemType.TableName = "ItemType";

            WorkbookDesigner designer = new WorkbookDesigner();
            string path = System.IO.Path.Combine(Application.StartupPath, "Report2-1.xls");
            designer.Open(path);
            designer.SetDataSource(dtBigType);
            designer.SetDataSource(dtItemType);
            designer.SetDataSource("YearMonth", dtBigType.Rows[0]["YearMonth"].ToString());
            designer.Process();

            //Save the excel file
            string fileToSave = FileDialogHelper.SaveExcel();
            if (File.Exists(fileToSave))
            {
                File.Delete(fileToSave);
            }
            designer.Save(fileToSave, FileFormatType.Excel2003);
            Process.Start(fileToSave);
        } 复制代码

 
通过绑定两个不同的DataTable对象,然后引用他的属性即可,行会自动增加以适应实际的数据,并且对象变量&=$YearMonth也正常显示了,注意一点就是,所有使用变量的地方,都必须在一个独立的Excel单元格中,否则不能解析出来。另外上图的红色圆圈里面表示,汇总的函数,会自动根据行列的增加,自动调整引用,这真是我们需要的。 

 

 出库单的实现也差不多,实现代码如下所示:

复制代码             string TakeOutBill = Path.Combine(Application.StartupPath, "TakeOutBill.xls");
            WorkbookDesigner designer = new WorkbookDesigner();
            designer.Open(TakeOutBill);
            designer.SetDataSource("TakeOutDate", DateTime.Now.ToString("yyyy-MM-dd"));
            designer.SetDataSource("WareHouse", this.txtWareHouse.Text);
            designer.SetDataSource("Manager", this.txtCreator.Text);
            designer.SetDataSource("CostCenter", this.txtCostCenter.Text);
            designer.SetDataSource("Dept", this.txtDept.Text);

            string columns = "Start|int,ItemNo,ItemName,Specification,Unit,Price|decimal,Count|int";
            DataTable dt = DataTableHelper.CreateTable(columns);
            dt.TableName = "Detail";
            DataRow row = null;
            for (int i = 0; i < this.lvwDetail.Items.Count; i++)
            {
                PurchaseDetailInfo info = this.lvwDetail.Items[i].Tag as PurchaseDetailInfo;
                if (info != null)
                {
                    row = dt.NewRow();
                    row["Start"] = (i + 1);
                    row["ItemNo"] = info.ItemNo;
                    row["ItemName"] = info.ItemName;
                    row["Specification"] = info.Specification;
                    row["Unit"] = info.Unit;
                    row["Price"] = info.Price;
                    row["Count"] = Math.Abs(info.Quantity);
                    dt.Rows.Add(row);
                }
            }
            designer.SetDataSource(dt);
            designer.Process();
            string fileToSave = FileDialogHelper.SaveExcel();
            if (File.Exists(fileToSave))
            {
                File.Delete(fileToSave);
            }
            designer.Save(fileToSave, FileFormatType.Excel2003);
            Process.Start(fileToSave);  复制代码

 

以上报表,其实实现思路基本都差不多,相对来时,还是比较容易的,接下来设计一个比较困难的报表,需要结合Aspose.Cell一些对象来动态创建行列,并设置单元格的变量,然后填入相应的对象构造报表,另外还需要注意单元格格式的变化,如下所示的这种报表

 

这个报表初看没有太多特别的地方,难点就是他的第一行列也是变化的,因此不能通过普通的方式构建二维表,然后绑定数据源的方式,要先加载模板文件,然后操作Excel对象,把第一行的各列头部补齐,然后给下一行各单元格填入对象公式,如&=BigType.DeptName 和&=BigType.TotalMoney等内容,实现的代码如下所示:

复制代码             string sql = @"Select [YearMonth], [DeptName], [ItemType], [TotalMoney]
                           from TB_ReportDeptCost ";
            DataTable dt = GetTable(sql);
            if (dt.Rows.Count == 0)
                return;

            List<string> itemTypeList = new List<string>();
            List<string> partList = new List<string>();
            foreach (DataRow row in dt.Rows)
            {
                string itemType = row["ItemType"].ToString();
                if (!itemTypeList.Contains(itemType))
                {
                    itemTypeList.Add(itemType);
                }

                string part = row["DeptName"].ToString();
                if (!partList.Contains(part))
                {
                    partList.Add(part);
                }
            }

            string columnString = "DeptName";
            for (int i = 0; i < itemTypeList.Count; i++)
            {
                columnString += string.Format(",TotalMoney{0}|decimal", i);
            }
            DataTable dtBigType = DataTableHelper.CreateTable(columnString);
            dtBigType.TableName = "BigType";
            foreach (string part in partList)
            {
                DataRow row = dtBigType.NewRow();
                row["DeptName"] = part;
                for (int i = 0; i < itemTypeList.Count; i++)
                {
                    string itemType = itemTypeList[i];
                    DataRow[] rowSelect = dt.Select(string.Format("DeptName='{0}' AND ItemType='{1}'", part, itemType));
                    if (rowSelect.Length > 0)
                    {
                        row["TotalMoney" + i.ToString()] = rowSelect[0]["TotalMoney"];
                    }
                }
                dtBigType.Rows.Add(row);
            }

            WorkbookDesigner designer = new WorkbookDesigner();
            string path = System.IO.Path.Combine(Application.StartupPath, "Report1.xls");
            designer.Open(path);

            Aspose.Cells.Worksheet w = designer.Workbook.Worksheets[0];
            //先设置标题项目:如大修件,日常备件等
            int rowIndex = 2;//第三行为标题
            Aspose.Cells.Style style = w.Cells[rowIndex + 1, 1].Style;//继承数字栏目的样式
            style.Number = 4;//对应格式是#,##0.00
            Aspose.Cells.Style boldStyle = w.Cells[rowIndex, 0].Style;//继承开始栏目的样式
            for (int i = 0; i < itemTypeList.Count; i++)
            {
                w.Cells[rowIndex, i + 1].PutValue(itemTypeList[i]);
                w.Cells[rowIndex, i + 1].Style = boldStyle;
                w.Cells[rowIndex + 1, i + 1].PutValue("&=BigType.TotalMoney" + i.ToString());
                w.Cells[rowIndex + 1, i + 1].Style = style;
            }

            //添加合计行
            w.Cells[rowIndex, itemTypeList.Count + 1].PutValue("合计");
            w.Cells[rowIndex, itemTypeList.Count + 1].Style = boldStyle;
            w.Cells[rowIndex + 1, itemTypeList.Count + 1].PutValue(string.Format("&=&=SUM(B{{r}}:{0}{{r}})", GetChar(itemTypeList.Count + 1)));
            w.Cells[rowIndex + 1, itemTypeList.Count + 1].Style = style;

            designer.SetDataSource(dtBigType);
            designer.SetDataSource("YearMonth", dt.Rows[0]["YearMonth"].ToString());
            designer.Process();

            //Save the excel file
            string fileToSave = FileDialogHelper.SaveExcel();
            if (File.Exists(fileToSave))
            {
                File.Delete(fileToSave);
            }
            designer.Save(fileToSave, FileFormatType.Excel2003);
            Process.Start(fileToSave);   复制代码

标签:控件,designer,string,rowIndex,Cells,Excel,Cell,fileToSave,row
From: https://www.cnblogs.com/spring_wang/p/14692471.html

相关文章

  • 用sql语句查询出表结构,在结果就能看到数据库所有表的结构,这个时候只要全选,然后右击出
    SELECT表名=CaseWhenA.colorder=1ThenD.nameElse''End,表说明=CaseWhenA.colorder=1Thenisnull(F.value,'')Else''End,字段序号=A.colorder,字段名=A.name,字段说明=isnull(G.[value],......
  • 掌握这些技巧,让Excel批量数据清洗变得简单高效!
    什么是数据清洗数据清洗是指在数据处理过程中对原始数据进行筛选、转换和修正,以确保数据的准确性、一致性和完整性的过程。它是数据预处理的一部分,旨在处理和纠正可能存在的错误、缺失值、异常值和不一致性等数据质量问题。为什么要数据清洗Excel在数据采集场景中非常常用。作......
  • WPF-细说控件Control
    ContentControls内容控件基本概念1.内容控件的最大的特征就是有一个Content属性继承关系2.1ButtonBaseFrameworkElement->Control->ContentControl->ButtonBase->Button,RepeatButton,GridViewColumnHeader,ToggleButton->CheckBox,RadioButton2.2HeaderedContentContro......
  • 怎么根据excel里面的内容和邮箱地址,生成pdf,并发送给对应邮箱
    Craftedby[Genie](https://marketplace.visualstudio.com/items?itemName=genieai.chatgpt-vscode)You怎么根据excel里面的内容和邮箱地址,生成pdf,并发送给对应邮箱Genie要根据Excel文件中的内容和邮箱地址生成PDF并发送到相应的邮箱,你可以使用Python编程语言来完成这个任......
  • unity3d-控件 Controls
    ControlTypes控件类型ThereareanumberofdifferentGUIControlsthatyoucancreate.ThissectionlistsalloftheavailabledisplayandinteractiveControls.ThereareotherGUIfunctionsthataffectlayoutofControls,whicharedescribedintheLayout......
  • 表单控件拖拽平台都有哪些特点?
    什么样的表单控件拖拽平台可以提升办公协作效率?在竞争激烈的当今社会,利用低代码技术平台的优势和特点,可以将企业内部的数据资源真正利用起来,帮助更多领域的客户朋友做出更有竞争优势的经营决策,实现数字化转型和流程化办公。什么是表单控件拖拽平台?要了解这个问题就需要了解低代码......
  • Python 合并Excel文件(Excel文件多sheet)
    一、Python合并Excel文件多sheet《方法1》importosimportpandasaspd#指定包含Excel文件的文件夹路径folder_path='C:\\Users\\Admin\\Desktop\\数据核对'#获取文件夹中的所有Excel文件excel_files=[fileforfileinos.listdir(folder_path)iffile.endswith......
  • 2023版:深度比较几种.NET Excel导出库的性能差异
    2023版:深度比较几种.NETExcel导出库的性能差异 2023版:深度比较几种.NETExcel导出库的性能差异引言背景和目的本文介绍了几个常用的电子表格处理库,包括EPPlus、NPOI、Aspose.Cells和DocumentFormat.OpenXml,我们将对这些库进行性能测评,以便为开发人员提供实际的性能指标和......
  • excel柱状图自定x轴y轴
    在Excel中,柱状图是一种常用的数据可视化方式,可以直观地展示不同数据之间的比较关系。默认情况下,Excel会根据数据自动生成X轴和Y轴的刻度和标签。然而,如果你想要自定义X轴和Y轴,在柱状图中显示特定的标签或调整刻度,Excel也提供了相应的功能。以下是详细介绍说明:1.创建柱状图: ......
  • pandas读取一个文件夹下所有excel表格中的第三个sheet,怎么破?
    大家好,我是皮皮。一、前言前几天在Python最强王者交流群【wen】问了一个Python自动化办公的问题,一起来看看吧。请教,pandas读取一个文件夹下所有excel表格中的第三个sheet,但是不同的excel的第三个sheetname也不同,怎么设定参数比较方面呢?二、实现过程这里【哎呦喂 是豆子~】......