利用Aspose.Cells导出Excel

public void ExportExcel(DataTable dt)
        {
            try
            {
                //获取指定虚拟路径的物理路径
                string path = HttpContext.Current.Server.MapPath("DLL/") + "License.lic";

                //读取 License 文件
                Stream stream = (Stream)File.OpenRead(path);

                //注册 License
                Aspose.Cells.License li = new Aspose.Cells.License();
                li.SetLicense(stream);

                //创建一个工作簿
                Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();

                //创建一个 sheet 表
                Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0];

                //设置 sheet 表名称
                worksheet.Name = dt.TableName;

                Aspose.Cells.Cell cell;

                int rowIndex = 0;   //行的起始下标为 0
                int colIndex = 0;   //列的起始下标为 0

                //设置列名
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    //获取第一行的每个单元格
                    cell = worksheet.Cells[rowIndex, colIndex + i];

                    //设置列名
                    cell.PutValue(dt.Columns[i].ColumnName);

                    //设置字体
                    cell.Style.Font.Name = "Arial";

                    //设置字体加粗
                    cell.Style.Font.IsBold = true;

                    //设置字体大小
                    cell.Style.Font.Size = 12;

                    //设置字体颜色
                    cell.Style.Font.Color = System.Drawing.Color.Black;

                    //设置背景色
                    cell.Style.BackgroundColor = System.Drawing.Color.LightGreen;
                }

                //跳过第一行,第一行写入了列名
                rowIndex++;

                //写入数据
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    for (int j = 0; j < dt.Columns.Count; j++)
                    {
                        cell = worksheet.Cells[rowIndex + i, colIndex + j];

                        cell.PutValue(dt.Rows[i][j]);
                    }
                }

                //自动列宽
                worksheet.AutoFitColumns();

                //设置导出文件路径
                path = HttpContext.Current.Server.MapPath("Export/");

                //设置新建文件路径及名称
                string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".xlsx";

                //创建文件
                FileStream file = new FileStream(savePath, FileMode.CreateNew);

                //关闭释放流,不然没办法写入数据
                file.Close();
                file.Dispose();

                //保存至指定路径
                workbook.Save(savePath);


                //或者使用下面的方法,输出到浏览器下载。
                //byte[] bytes = workbook.SaveToStream().ToArray();
                //OutputClient(bytes);

                worksheet = null;
                workbook = null;
            }
            catch(Exception ex)
            {

            }
        }
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页