C# 使用NPOI导出Excel,首行冻结,添加筛选,填充颜色,列宽自适应
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# 使用NPOI导出Excel,首行冻结,添加筛选,填充颜色,列宽自适应,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2263字,纯文字阅读大概需要4分钟。
内容图文
![C# 使用NPOI导出Excel,首行冻结,添加筛选,填充颜色,列宽自适应](/upload/InfoBanner/zyjiaocheng/814/293db3010f50480891b6f34e4c650427.jpg)
使用NuGet安装NPOI,添加以下命名空间
using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel;
添加类 ExcelExporter
public static class ExcelExporter { /// <summary> /// DataTable导出Excel /// </summary> /// <param name="dataTable">数据源</param> /// <param name="fileName">保存的文件名</param> /// <param name="sheetName">表名</param> public static void ExportToExcel(this DataTable dataTable, string fileName, string sheetName = "Sheet1") { if (dataTable == null || dataTable.Rows.Count == 0) throw new Exception("No data to export"); ISheet sheet = null; IWorkbook workbook = null; try { using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); else throw new NotSupportedException("Not supported file extension"); if (string.IsNullOrEmpty(sheetName)) sheetName = "Sheet1"; sheet = workbook.CreateSheet(sheetName); ICellStyle headerStyle = workbook.CreateCellStyle(); //首行填充黄色 headerStyle.FillForegroundColor = IndexedColors.Yellow.Index; headerStyle.FillPattern = FillPattern.SolidForeground; IRow row = sheet.CreateRow(0); for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { var cell = row.CreateCell(columnIndex); cell.CellStyle = headerStyle; cell.SetCellValue(dataTable.Columns[columnIndex].ColumnName); //设置列名 } for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++) { row = sheet.CreateRow(rowIndex + 1); for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { row.CreateCell(columnIndex).SetCellValue(Convert.ToString(dataTable.Rows[rowIndex][columnIndex])); } } for (int columnIndex = 0; columnIndex < dataTable.Columns.Count; columnIndex++) { sheet.AutoSizeColumn(columnIndex); //自适应宽度 } sheet.SetAutoFilter(new CellRangeAddress(0, 0, 0, dataTable.Columns.Count - 1)); //首行筛选 sheet.CreateFreezePane(dataTable.Columns.Count, 1); //首行冻结 workbook.Write(fs); //写入到excel } } finally { if (workbook != null) workbook.Close(); } } }
使用时传入文件路径,即可将DataTable导出到指定位置。
如要导出集合类数据IEnumerable<T>,使用反射转成DataTable即可。方法大同小异,这里就不写了
内容总结
以上是互联网集市为您收集整理的C# 使用NPOI导出Excel,首行冻结,添加筛选,填充颜色,列宽自适应全部内容,希望文章能够帮你解决C# 使用NPOI导出Excel,首行冻结,添加筛选,填充颜色,列宽自适应所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。