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;
            }
  • 相关阅读:
    DP_knapsack
    也谈交换两个变量
    SidebySide Assembly
    Generate permutation for N elements
    Pixel Shader 像素着色
    Drill into View Matrix
    使用D3DXCreateSphere绘图的步骤
    原来VisualStudio本身也可以查看调试信息
    DirectX Effects初探
    Shortcuts
  • 原文地址:https://www.cnblogs.com/Archosaur/p/DataSourceToExcel.html
Copyright © 2011-2022 走看看