c# Aspose.Cells 导出Excel表格 使用随记

/// <summary>
        /// 导出Excel表格
        /// </summary>
        /// <param name="list">数据集合</param>
        /// <param name="header">数据表头</param>
        /// <param name="sumColumn">求和列</param>
       /// <param name=" title"> 标题</param>
        /// <returns></returns>
        public static void ExportExcel(DataTable dt, string[] header, string sumColumn=null, string title = null)
        {
            //Workbook wb = new Workbook(FileFormatType.Xlsx);
            Workbook wb = new Workbook();
            try
            {
                Worksheet sheet = wb.Worksheets[0];
                sheet.Name = "MO上行查询结果";
                if (dt.Rows.Count <= 0)
                {
                    System.Web.HttpContext.Current.Response.Write("<script>alert('没有检测到需要导出数据!');</script>");
                    return;
                }


                // 为单元格添加样式
                Aspose.Cells.Style style = wb.CreateStyle();
                //style.HorizontalAlignment = Aspose.Cells.TextAlignmentType.Center;  //设置居中
                style.Font.Size = 20;//文字大小
                style.Font.IsBold = true;//粗体
                style.HorizontalAlignment = TextAlignmentType.Center;//文字居中
                                                                 

                // 为合计单元格样式
                Aspose.Cells.Style sumstyle =  wb.CreateStyle();
                sumstyle.Font.Size = 12;//文字大小
                sumstyle.Font.IsBold = true;//粗体
                sumstyle.Font.Color = Color.Red;   //颜色
                //style.HorizontalAlignment = TextAlignmentType.Center;//文字居中
                

                //添加标题
                int rowIndex = 0;
                sheet.Cells.SetRowHeight(rowIndex, 40); //设置行高
                if (title!=null)
                {
                    sheet.Cells[rowIndex, 0].PutValue(title);
                    sheet.Cells[rowIndex, 0].SetStyle(style);
                    sheet.Cells.Merge(0, 0, 1, header.Length); //合并行 Merge(1, 1,1, 5); 第一行 第一列 到 第一行 第 5列  
                                                                                        //Merge切记后两位参数不能是 0 
                    rowIndex++;
                }


                //添加表头
                style.Font.Size = 12;//文字大小
                sheet.Cells.SetRowHeight(rowIndex, 20); //设置行高
                for (int c = 0; c < header.Length; c++)
                {
                    
                    sheet.Cells[rowIndex, c].PutValue(header[c]);
                    sheet.Cells[rowIndex, c].SetStyle(style);
                    sheet.Cells.SetColumnWidth(c, 20);//设置宽度

                    //设置求和列公试
                    if (sumColumn != null && sumColumn.IndexOf(header[c]) > -1)
                    {
                        string sn = sheet.Cells[rowIndex + 1, c].Name;
                        string en = sheet.Cells[rowIndex + dt.Rows.Count, c].Name;
                        sheet.Cells[rowIndex + dt.Rows.Count + 1, c].SetStyle(sumstyle);
                        sheet.Cells[rowIndex + dt.Rows.Count + 1, c].Formula = "=SUM(" + sn + ":" + en + ")"; //设置单元格公式     
                    }
                }
                rowIndex++;

                //添加内容
                for (int r = 0; r < dt.Rows.Count; r++)//遍历DataTable行
                {

                    for (int c = 0; c < header.Length; c++) //列只遍历到和表头数量相等的列,其余的列不导出
                    {
                        //自动把数字变量转出后 单元格变为数字类型。
                        try
                        {
                            Convert.ToDecimal(dt.Rows[r][c]);
                            sheet.Cells[r + rowIndex, c].PutValue(Convert.ToDecimal(dt.Rows[r][c])); //要导出数字列是数字类型,必须把添加变量转数字类型。
                        }
                        catch { sheet.Cells[r + rowIndex, c].PutValue(dt.Rows[r][c].ToString()); }
                    }
                }
                //输出到Excel  直接输出到浏览器
                wb.Save(HttpContext.Current.Response, DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".xlsx",        ContentDisposition.Attachment, new OoxmlSaveOptions(SaveFormat.Xlsx));
               //保存成97或2003写法
               //workbook.Save(HttpContext.Current.Response, “output.xls”, ContentDisposition.Attachment, New XlsSaveOptions(SaveFormat.Excel97To2003))
                HttpContext.Current.Response.End();  //一定要结束HttpContext.Current.Response

            // 释放Excel对象
              Marshal.ReleaseComObject(sheet);
              Marshal.ReleaseComObject(wb);
            }
            catch (Exception e)
            {
                System.Web.HttpContext.Current.Response.Write("<script>alert('导出异常:" + e.Message + "!');</script>");
            }
            
        }

        #endregion
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Aspose.Cells是一个用于处理Excel文件的.NET组件。在使用Aspose.Cells导出Excel文件时,可以使用以下代码示例: ```csharp System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; workbook.Save(Response, HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8) + ".xlsx", Aspose.Cells.ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions(Aspose.Cells.SaveFormat.Xlsx)); ``` 这段代码将Excel文件保存到HttpResponse中,以便将其作为附件下载。其中,`workbook`是你创建的Excel工作簿对象,`filename`是你想要保存的文件名。 在生成Excel文件时,你还可以设置标题行和列头行的样式,例如: ```csharp // 生成标题行 cells.Merge(0, 0, 1, header.Keys.Count); // 合并单元格,标题行有几列就合并几列 cells\[0, 0\].PutValue(filename); // 填写内容 cells\[0, 0\].SetStyle(styleTitle); // 使用标题样式 cells.SetRowHeight(0, 50); // 第0行,50px高 // 生成列头行 int headerNum = 0; // 当前表头所在列 foreach (string item in header.Keys) { cells\[1, headerNum\].PutValue(item); cells\[1, headerNum\].SetStyle(styleHeader); cells.SetColumnWidthPixel(headerNum, 200); // 设置单元格200宽度 cells.SetRowHeight(1, 30); // 第一行,30px高 headerNum++; } ``` 这段代码示例展示了如何设置标题行和列头行的样式,其中`cells`是你创建的Worksheet对象,`header`是一个包含列头信息的字典,`styleTitle`和`styleHeader`是你定义的样式对象。 希望这些代码示例能帮助到你导出Excel文件使用Aspose.Cells。 #### 引用[.reference_title] - *1* *2* *3* [使用Aspose.Cells导出excel](https://blog.csdn.net/rxbtalent/article/details/99818241)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值