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

发布时间 : 星期六 文章使用Aspose.Cell控件实现Excel高难度报表的生成(三)更新完毕开始阅读

报表中最复杂的是表头的生成,因为它是不规则的表头,因此需要很细的操作Cell和Range对象,实现复杂表头(也是很常见的)的生成。

这个是慢工出细活,需要对Cell和Range熟悉使用,然后给他们分配不同的行列就可以生成一个标准如下的表头了。

Style headStyle = CreateStyle(workbook, true); Style normalStyle = CreateStyle(workbook, false); int startRow = 4;

range = worksheet.Cells.CreateRange(startRow, 0, 2, 1); range.Merge();

range.Style = headStyle; cell = range[0, 0]; cell.PutValue(\序号\ cell.Style = headStyle;

range = worksheet.Cells.CreateRange(startRow, 1, 2, 1); range.Merge();

range.Style = headStyle; range.ColumnWidth = 40; cell = range[0, 0]; cell.PutValue(\疾病名称\ cell.Style = headStyle;

int startCol = 2;

foreach (string deptName in DeptNameList) {

range = worksheet.Cells.CreateRange(startRow, startCol, 1, 2);

range.Merge();

range.Style = headStyle; cell = range[0, 0]; cell.PutValue(deptName);

cell = worksheet.Cells[startRow + 1, startCol]; cell.PutValue(\人次\ cell.Style = headStyle;

cell = worksheet.Cells[startRow + 1, startCol + 1]; cell.PutValue(\百分比\ cell.Style = headStyle;

startCol += 2; }

range = worksheet.Cells.CreateRange(startRow, startCol, 1, 2);

range.Merge();

range.Style = headStyle; cell = range[0, 0]; cell.PutValue(\合计\

cell = worksheet.Cells[startRow + 1, startCol]; cell.PutValue(\人次\ cell.Style = headStyle;

cell = worksheet.Cells[startRow + 1, startCol + 1]; cell.PutValue(\百分比\ cell.Style = headStyle; #endregion

3、填入表格内容 这个不算复杂,只需要遍历然后生成内容到单元格即可。

//写入数据到Excel

startRow = startRow + 2; for (int i = 0; i < dt.Rows.Count; i++) {

startCol = 0;

for (int j = 0; j < dt.Columns.Count; j++) {

DataRow dr = dt.Rows[i];

cell = worksheet.Cells[startRow, startCol]; cell.PutValue(dr[j]); cell.Style = normalStyle;

startCol++; }

startRow++; }

4、插入图表及导出打开操作 这个Apose.Cell控件的WorkSheet提供了worksheet.Pictures.Add方法,可以添加图片的操作,不过图片是通过流方式写入,我们把图表的Image对象转换一下,创建一个内存流就可以了。如下所示。

//写入图注

startRow += 1;//跳过1行

range = worksheet.Cells.CreateRange(startRow++, 0, 1, colSpan);

range.Merge(); range.RowHeight = 15; cell = range[0, 0];

cell.PutValue(\以柱状图展示如下:\);

//插入图片到Excel里面 byte[] bytes =

ImageHelper.ImageToBytes(this.pictureBox1.Image);

using (MemoryStream stream = new MemoryStream(bytes)) {

worksheet.Pictures.Add(startRow, 0, stream); }

//Save the excel file. string saveFile =

FileDialogHelper.SaveExcel(\, \);

if (!string.IsNullOrEmpty(saveFile)) {

workbook.Save(saveFile);

if (MessageUtil.ShowYesNoAndTips(\保存成功,是否打开文件?\) == System.Windows.Forms.DialogResult.Yes) {

System.Diagnostics.Process.Start(saveFile); } }

至此,基于Apose.Cell的自定义报表的另外一种操作也全部实现了,为了实现这个简单的例子,以便在项目中使用,花了不少时间,不过以后对于生成这类复杂的和自定义报表,可以直接利用它们基础的对象进行操作即可;

如果是一些常规的报表,可以利用自定义模板的方式生成,然后绑定数据源;如果是二维表,或者ILIst集合,导出Excel就更简单了。以上两种都可以直接利用封装好的

AsposeExcelTools来进行操作,这个通用的类库,可以省却每次去编写代码的繁琐,提高效率。

联系合同范文客服:xxxxx#qq.com(#替换为@)