如何用C#导出Excel表格
1个回答
展开全部
利用NPOI可以将DataTable的数据到出成为Excel,相关代码如下:
/// <summary> /// 导出数据 /// </summary> /// <param name="table">表数据</param> /// <param name="columns">列名</param> /// <returns></returns> public static MemoryStream RenderToExcel(DataTable table, string[] columns) { MemoryStream ms = new MemoryStream(); IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IRow headerRow = sheet.CreateRow(0); for (var i = 0; i < columns.Length; i++) headerRow.CreateCell(i).SetCellValue(columns[i]); int rowIndex = 1; foreach (DataRow row in table.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in table.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; }这段代码是将DataTable的数据转成流,剩余的你将流变成文件保存就行了。
/// <summary> /// 导出数据 /// </summary> /// <param name="table">表数据</param> /// <param name="columns">列名</param> /// <returns></returns> public static MemoryStream RenderToExcel(DataTable table, string[] columns) { MemoryStream ms = new MemoryStream(); IWorkbook workbook = new HSSFWorkbook(); ISheet sheet = workbook.CreateSheet(); IRow headerRow = sheet.CreateRow(0); for (var i = 0; i < columns.Length; i++) headerRow.CreateCell(i).SetCellValue(columns[i]); int rowIndex = 1; foreach (DataRow row in table.Rows) { IRow dataRow = sheet.CreateRow(rowIndex); foreach (DataColumn column in table.Columns) { dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString()); } rowIndex++; } workbook.Write(ms); ms.Flush(); ms.Position = 0; return ms; }这段代码是将DataTable的数据转成流,剩余的你将流变成文件保存就行了。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询