zoukankan      html  css  js  c++  java
  • 将数据导出至Excel(标准Excel)

           private static Stream ExportDataTableToExcel(DataTable sourceTable, string sheetName)
            {
                HSSFWorkbook workbook = new HSSFWorkbook();
                MemoryStream ms = new MemoryStream();
                ISheet sheet = workbook.CreateSheet(sheetName);
                IRow headerRow = sheet.CreateRow(0);
                // handling header.
                foreach (DataColumn column in sourceTable.Columns)
                    headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
    
                // handling value.
                int rowIndex = 1;
    
                foreach (DataRow row in sourceTable.Rows)
                {
                    IRow dataRow = sheet.CreateRow(rowIndex);
    
                    foreach (DataColumn column in sourceTable.Columns)
                    {
                        dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                    }
    
                    rowIndex++;
                }
    
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
    
                sheet = null;
                headerRow = null;
                workbook = null;
    
                return ms;
            }
            /// <summary>
            /// 由DataTable导出Excel
            /// </summary>
            /// <param name="sourceTable">要导出数据的DataTable</param>
            /// <param name="fileName">指定Excel工作表名称</param>
            /// <returns>Excel工作表</returns>
            public static void ExportDataTableToExcel(DataTable sourceTable, string fileName, string sheetName)
            {
                MemoryStream ms = ExportDataTableToExcel(sourceTable, sheetName) as MemoryStream;
                HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
                HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                HttpContext.Current.Response.BinaryWrite(ms.ToArray());
                HttpContext.Current.Response.End();
                ms.Close();
                ms = null;
            }
  • 相关阅读:
    提高PHP运行速度的几大方法
    如何判断Javascript对象是否存在
    CSS属性选择器中的通配符
    jQuery对象与dom对象的转换
    jquery的clone方法bug的修复
    IntelliJ IDEA 开发工具项目maven管理
    Socket连接与HTTP连接
    C#枚举数值与名称的转换
    JSSDK制作思路
    iOS强制横竖屏转换
  • 原文地址:https://www.cnblogs.com/Archosaur/p/DataSourceToExcel.html
Copyright © 2011-2022 走看看