星空网 > 软件开发 > ASP.net

C#导出Excel那些事

Excel导出

Excel导出的意义

因为在项目中有些报表数据客户需要导出功能,那么导出为Excel就十分有必要了,可是有些客户的机器上并没有安装Excel或者安装的版本参差不一。
那么我们在这样的情况下应该应该怎么做呢?最简单的方法就是引用Excel相关的Com组件就行了,可是这种情况只能在安装了Excel的用户适用,
对于没有安装Excel的用户不能强制用户安装吧。那么我们只能将眼光瞄向第三方的类库了,能用的Excel操作导出类库大致有这么三个
  1. NPOI
  2. ExcelRepor
  3. aspose.cells

    好的,废话不多说,接下来就将这几种导出方法一一道来:首先我们模拟一个数据源

C#导出Excel那些事C#导出Excel那些事
 1     private DataTable dt = new DataTable(); 2  3     /// <summary> 4     /// 装载数据 5     /// </summary> 6     private void Inidata() 7     { 8       dt.TableName = "student"; 9       dt.Columns.Add("Name", typeof(string));10       dt.Columns.Add("Team", typeof(string));11       DataRow dr = dt.NewRow();12       DataRow dr1 = dt.NewRow();13       dr["Name"] = "科比";14       dr["Team"] = "湖人";15       dt.Rows.Add(dr);16       dr1["Name"] = "詹姆斯";17       dr1["Team"] = "骑士";18       dt.Rows.Add(dr1);19       list.Add(new Student { Name = "科比", Team = "湖人" });20       list.Add(new Student { Name = "詹姆斯", Team = "骑士" });21     }

View Code

 

使用NPOI导出

NPOI 是 POI 项目的 .NET 版本。具体的信息请自行百度。下边是我们公司用的一个NPOI到处的Helper中的片段
C#导出Excel那些事C#导出Excel那些事
 1 public class NPOIExportExclHelper 2   { 3     /// <summary> 4     /// 创建一个Excel 5     /// Yakecan 6     /// </summary> 7     /// <returns>返回一个空表格</returns> 8     public HSSFWorkbook InitializeWorkBook() 9     { 10       HSSFWorkbook workBook = new HSSFWorkbook(); 11       DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 12       SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 13  14       dsi.Company = "河南xx软件科技有限公司"; 15       dsi.Manager = "Office Word 2003/2007"; 16  17       si.Author = "www.henanluheng.com"; 18       si.Subject = "信息导出"; 19       si.Title = "系统报表"; 20  21       workBook.DocumentSummaryInformation = dsi; 22       workBook.SummaryInformation = si; 23  24       return workBook; 25     } 26  27      28     /// <summary> 29     /// 把指定的DataTable导出Excel 30     /// Yakecan 31     /// </summary> 32     /// <param name="dt">数据源</param> 33     /// <param name="path">导出的路径(包含文件的名称及后缀名)</param> 34     /// <param name="tittle">Sheet的名称</param> 35     public void Export(DataTable dt, string path, string tittle) 36     { 37       HSSFWorkbook workbook = InitializeWorkBook(); 38       ISheet sheet1 = workbook.CreateSheet(tittle); 39  40       IRow titleRow = sheet1.CreateRow(0); 41       titleRow.Height = (short)20 * 25; 42  43       ICellStyle titleStyle = workbook.CreateCellStyle(); 44       titleStyle.Alignment = HorizontalAlignment.Center; 45       titleStyle.VerticalAlignment = VerticalAlignment.Center; 46       IFont font = workbook.CreateFont(); 47       font.FontName = "宋体"; 48       font.FontHeightInPoints = (short)16; 49       titleStyle.SetFont(font); 50  51       NPOI.SS.Util.CellRangeAddress region = new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dt.Columns.Count); 52       sheet1.AddMergedRegion(region); // 添加合并区域 53  54       ICell titleCell = titleRow.CreateCell(0); 55       titleCell.CellStyle = titleStyle; 56       titleCell.SetCellValue(tittle); 57  58  59       IRow headerRow = sheet1.CreateRow(1); 60       ICellStyle headerStyle = workbook.CreateCellStyle(); 61       headerStyle.Alignment = HorizontalAlignment.Center; 62       headerStyle.VerticalAlignment = VerticalAlignment.Center; 63       headerStyle.BorderBottom = BorderStyle.Thin; 64       headerStyle.BorderLeft = BorderStyle.Thin; 65       headerStyle.BorderRight = BorderStyle.Thin; 66       headerStyle.BorderTop = BorderStyle.Thin; 67       IFont titleFont = workbook.CreateFont(); 68       titleFont.FontHeightInPoints = (short)11; 69       titleFont.FontName = "宋体"; 70       headerStyle.SetFont(titleFont); 71  72       headerRow.CreateCell(0).SetCellValue("序号"); 73       headerRow.GetCell(0).CellStyle = headerStyle; 74  75       for (int i = 0; i < dt.Columns.Count; i++) 76       { 77         headerRow.CreateCell(i + 1).SetCellValue(dt.Columns[i].ColumnName); 78         headerRow.GetCell(i + 1).CellStyle = headerStyle; 79         sheet1.SetColumnWidth(i, 256 * 18); 80       } 81  82       ICellStyle bodyStyle = workbook.CreateCellStyle(); 83       bodyStyle.BorderBottom = BorderStyle.Thin; 84       bodyStyle.BorderLeft = BorderStyle.Thin; 85       bodyStyle.BorderRight = BorderStyle.Thin; 86       bodyStyle.BorderTop = BorderStyle.Thin; 87       for (int r = 0; r < dt.Rows.Count; r++) 88       { 89         IRow bodyRow = sheet1.CreateRow(r + 2); 90         bodyRow.CreateCell(0).SetCellValue(r + 1); 91         bodyRow.GetCell(0).CellStyle = bodyStyle; 92         bodyRow.GetCell(0).CellStyle.Alignment = HorizontalAlignment.Center; 93  94         for (int c = 0; c < dt.Columns.Count; c++) 95         { 96           bodyRow.CreateCell(c + 1).SetCellValue(dt.Rows[r][c].ToString()); 97           bodyRow.GetCell(c + 1).CellStyle = bodyStyle; 98         } 99       }100 101       sheet1.CreateFreezePane(1, 2);102 103       FileStream fs = new FileStream(path, FileMode.Create);104       workbook.Write(fs);105       fs.Flush();106       fs.Position = 0;107       sheet1 = null;108       headerRow = null;109       workbook = null;110       //OutPutExcelStreamOnClient(ms, xlsName);111       fs.Dispose();112     }113 114 115   }

View Code

好了,接下来让我们来使用一下这个导出的功能,导出代码如下,这些没什么技术含量,F5启动程序查看导出的效果

1 SaveFileDialog savedialog = ShowExportExcelDoalog();2       savedialog.FileName = "这是我的测试数据";3       if (savedialog.ShowDialog() == DialogResult.OK)4       {5         NPOIExportExclHelper excelHelper = new NPOIExportExclHelper();6         excelHelper.Export(dt, savedialog.FileName, "这是我的测试数据");7       }

OK,这是我们导出的效果图,自动为我们加上了序号这一列,不过整体来说导出的功能还是没有任何问题。不过还是有一点瑕疵,数据的列名还是英文,解决方法也很简单只要我们设置数据源的dt的列头名设置为中国文就行了,dt.Columns["Name"].ColumnName = "姓名"; 设置完成再导出就没问题了。对于我们直男程序员来说这样大致差不多也就完成了任务,可是这样的效果对于真正的生产环境来说还是不行的,因为有些客户还要求导出的Excel要有格式,比如标题高亮啊、数据行每行颜色的高亮。这些怎么办呢,这就用到接下来的方法了。

C#导出Excel那些事

使用ExcelReport和模板导出

使用模板导出Excel可以实现Excel的数据和样式的分离,虽然NPOI也可以导出的时候设置样式但是代码比较繁琐。

ExcelReport是博客园的一个大神韩兆新捣鼓出来的一个小工具。在QQ群中作者对于使用者遇到的问题和意见还是反馈的很积极的,这点要给作者点个赞的。关于这个控件的具体详细方法还请大家参考作者的一系列博客,下面只是给你导出的最基本的代码。

首先是我们的模板格式

C#导出Excel那些事

导出代码如下

 1 SaveFileDialog saveFileDlg = new SaveFileDialog(); 2       saveFileDlg.Filter = "Excel 2003文件|*.xls|Excel 2007文件|*.xlsx"; 3  4       if (DialogResult.OK.Equals(saveFileDlg.ShowDialog())) 5       { 6         //实例化一个参数容器,并加载模板填充规则文件 7  8         ParameterCollection collection = new ParameterCollection(); 9 10         collection.Load(@"Templete\excelreport.");11         //实例化一个元素格式化器列表12 13         List<ElementFormatter> formatters = new List<ElementFormatter>();14 15         formatters.Add(new CellFormatter(collection["Sheet1", "time"], "第一次"));  //添加一个单元格格式化器16         //添加一个Table格式化器17         formatters.Add(new TableFormatter<Student>(collection["Sheet1", "Name"].X, list,18           new TableColumnInfo<Student>(collection["Sheet1", "Name"].Y, t => t.Name),19           new TableColumnInfo<Student>(collection["Sheet1", "Team"].Y, t => t.Team))20           );21 22         //导出文件到本地23         ExportHelper.ExportToLocal(@"Templete\excelreport.xls", saveFileDlg.FileName,24           new SheetFormatterContainer("Sheet1", formatters));

 

使用aspose.cells和模板导出

Aspose是一个非常强大的“收费控件”,我们要用到的是aspose.cells,这个控件的使用不需要引用其他别的控件,其次代码也非常简单。具体的使用方法参考Aspose.Cells 根据Excel模板导出数据统计

模板如下

C#导出Excel那些事

 1 WorkbookDesigner designer = new WorkbookDesigner(); 2       //Server.MapPath("./")  3       string path = System.AppDomain.CurrentDomain.BaseDirectory + "/Templete/aspose.xls"; 4       designer.Open(path); 5       designer.SetDataSource(dt); 6       designer.Process(); 7       //Save the excel file 8       string fileToSave = System.AppDomain.CurrentDomain.BaseDirectory + "Templete/JH_ManageExcel.xls"; 9       if (File.Exists(fileToSave))10       {11         File.Delete(fileToSave);12       }13 14       designer.Save(fileToSave, FileFormatType.Excel2003);15       //打开Excel文件16       Process.Start(fileToSave);


总结


 

本文只是简单的介绍几种Excel的导出方法,并没有具体的深入研究。这三种方式各有各的特点,第一种方法比较通用,适合那些需要多种导出且对导出的样式没有要求的项目,后边两种适合那些对导出数据有样式需求的项目。第二种方式所用的类库开源、免费但是代码比较繁琐,且还需要生成



原标题:C#导出Excel那些事

关键词:C#

C#
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

michiny:https://www.ikjzd.com/w/4566
Mack Weldon:https://www.ikjzd.com/w/4567
趣发跨境东南亚运营中心:https://www.ikjzd.com/w/4568
melark:https://www.ikjzd.com/w/4569
Catch.com.au:https://www.ikjzd.com/w/457
郑州易联客:https://www.ikjzd.com/w/4570
E-Bike品牌EMotorad获战略融资!:https://www.kjdsnews.com/a/1840707.html
Shopee订单量激增5倍多,越南成韩国美容品牌主要消费市场:https://www.kjdsnews.com/a/1840708.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流