zoukankan      html  css  js  c++  java
  • Web C# 导出Excel 方法总结

    方法1:微软推荐服务器需安装Excel型

    依赖:

    软件:Office Excel 2007-2013

    引用:Microsoft Office 14.0 Object Library

    1.1 数据准备

     1 //Excel文件名称
     2     string ExcelName = System.DateTime.Now.ToString("yyMMdd") + "退款结算单.xlsx";
     3 
     4     /// <summary>
     5     /// 批量退款
     6     /// </summary>
     7     /// <param name="sender"></param>
     8     /// <param name="e"></param>
     9     protected void Button1_Click(object sender, EventArgs e)
    10     {
    11         DataSet ds = new DataSet();
    12 
    13         DataTable dt1 = new DataTable();
    14         dt1.Columns.Add("批次号");
    15         dt1.Columns.Add("总金额(元)");
    16         dt1.Columns.Add("总笔数");
    17 
    18         DataRow row1 = dt1.NewRow();
    19 
    20         row1 = dt1.NewRow();
    21         row1["批次号"] = "20150425001";
    22         row1["总金额(元)"] = "0.03";
    23         row1["总笔数"] = "1";
    24         dt1.Rows.Add(row1);
    25 
    26         ds.Tables.Add(dt1);
    27 
    28         DataTable dt2 = new DataTable();
    29         dt2.Columns.Add("商户订单号");
    30         dt2.Columns.Add("支付宝交易号");
    31         dt2.Columns.Add("退款金额");
    32         dt2.Columns.Add("退款备注");
    33 
    34         DataRow row2 = dt2.NewRow();
    35 
    36         row2 = dt2.NewRow();
    37         row2["商户订单号"] = "D150418092109-40";
    38         row2["支付宝交易号"] = "2015041800001000770049196543";
    39         row2["退款金额"] = "0.02";
    40         row2["退款备注"] = "导入excel测试";
    41         dt2.Rows.Add(row2);
    42 
    43         ds.Tables.Add(dt2);
    44 
    45 
    46         doExport(ds, Server.MapPath(ExcelName));
    47     }

    1.2 数据写入

     1  private Microsoft.Office.Interop.Excel.Application _Excel = null;
     2 
     3     /// <summary>
     4     /// 将 DataSet 数据写入 _Excel
     5     /// </summary>
     6     /// <param name="ds"></param>
     7     /// <param name="strExcelFileName"></param>
     8     private void doExport(DataSet ds, string strExcelFileName)
     9     {
    10         int rowIndex = 1;//当前行数
    11         int colIndex = 0;//当前列数
    12 
    13 
    14         _Excel = new Microsoft.Office.Interop.Excel.Application();
    15         _Excel.Application.Workbooks.Add(true);
    16 
    17 
    18         for (int i = 0; i < ds.Tables.Count; i++)
    19         {
    20             DataTable table = ds.Tables[i];
    21             colIndex = 0;//列初始化
    22             // 列标题
    23             foreach (DataColumn col in table.Columns)
    24             {
    25                 colIndex++;
    26                 _Excel.Cells[rowIndex, colIndex] = col.ColumnName;
    27             }
    28 
    29             // 内容
    30             foreach (DataRow row in table.Rows)
    31             {
    32                 rowIndex++;
    33                 colIndex = 0;
    34                 foreach (DataColumn col in table.Columns)
    35                 {
    36                     colIndex++;
    37                     _Excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
    38                 }
    39             }
    40 
    41             rowIndex++;//行+1 防止table又多个情况
    42         }
    43 
    44         _Excel.Visible = false;
    45         // 保存文件
    46         SaveToDisk(strExcelFileName);
    47 
    48         _Excel.Quit();
    49         _Excel = null;
    50     }

    1.3 数据导出

     1   /// <summary>
     2     /// 导出方法
     3     /// </summary>
     4     /// <param name="path">路径</param>
     5     private void SaveToDisk(string path)
     6     {
     7         if (!string.IsNullOrEmpty(path))
     8         {
     9             System.IO.FileInfo info = new FileInfo(path);
    10             if (!info.Exists)
    11             {
    12                 _Excel.ActiveWorkbook.SaveCopyAs(path);
    13 
    14                 /*
    15                 微软为Response对象提供了一个新的方法TransmitFile来解决使用Response.BinaryWrite
    16                 下载超过400mb的文件时导致Aspnet_wp.exe进程回收而无法成功下载的问题。
    17                 代码如下:
    18                */
    19                 Response.ContentType = "text/xml";
    20                 Response.AddHeader("Content-Disposition", "attachment;filename=" + ExcelName);
    21                 string filename = Server.MapPath(ExcelName);
    22                 Response.TransmitFile(filename);
    23             }
    24             else
    25             {
    26                 info.Delete();
    27                 _Excel.DisplayAlerts = false;
    28                 _Excel.AlertBeforeOverwriting = false;
    29                 _Excel.ActiveWorkbook.SaveCopyAs(path);
    30             }
    31         }
    32     }

    方法2:第三方组件NPOI(2.0版本后受到微软支持)

    依赖:

    NPOI.dll

    NPOI.OOXML.dll

    NPOI.OpenXml4Net.dll

    NPOI.OpenXmlFormats.dll

    NPOI下载地址 - http://npoi.codeplex.com/releases

    2.1 简单例子:

     1 using NPOI.XSSF.UserModel;
     2 using NPOI.SS.UserModel;
     3 
     4 //创建全新的Workbook
     5 IWorkbook workbook = new XSSFWorkbook();
     6 
     7 //创建Sheet
     8 workbook.CreateSheet("Sheet1");
     9 
    10 //写入一个简单日期 并设置格式
    11 ISheet sheet = hssfworkbook.CreateSheet("Sheet1");
    12 ICell cell = sheet.CreateRow(0).CreateCell(0);
    13 cell.SetCellValue(new DateTime(2008,5,5));
    14 //set date format
    15 ICellStyle cellStyle = hssfworkbook.CreateCellStyle();
    16 IDataFormat format = hssfworkbook.CreateDataFormat();
    17 cellStyle.DataFormat = format.GetFormat("yyyy年m月d日");
    18 cell.CellStyle=cellStyle;
    19 
    20 //保存Workbook
    21 FileStream sw = File.Create("test.xlsx");
    22 workbook.Write(sw);
    23 sw.Close();

    这样就好了。

    2.2 复杂例子(包含下载功能)

         /// <summary>
         /// 导出Excel
         /// </summary>
         /// <param name="ExcelName">文件名称</param>
         public void NPOIExcel(DataSet ds, string ExcelName)
         {
             int row_index = 0;
             //创建全新的Workbook
             IWorkbook workbook = new XSSFWorkbook();
     
     
             //创建Sheet
             workbook.CreateSheet("Sheet1");
    
             //根据Sheet名字获得Sheet对象
             ISheet sheet = workbook.GetSheet("Sheet1");
             IRow row;
     
             row = sheet.CreateRow(row_index);
             for (int i = 0; i < ds.Tables.Count; i++)
             {
                 //写入标题
                 for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                 {
                     row.CreateCell(j).SetCellValue(ds.Tables[i].Columns[j].Caption.ToString());
     
                 }
                 row = sheet.CreateRow(++row_index);
    
                 //写入数据
                 foreach (DataRow r in ds.Tables[i].Select())
                 {
                     for (int j = 0; j < ds.Tables[i].Columns.Count; j++)
                     {
                         row.CreateCell(j).SetCellValue(r[j].ToString());
                     }
     
                     row = sheet.CreateRow(++row_index);
                 }
     
     
             }
     
             //保存Workbook方式一: 以文件形式保存到服务器中(每次导出都会生成一个文件,慎重使用)
             FileStream sw = File.Create(Server.MapPath("file/" +ExcelName));
             workbook.Write(sw);
             sw.Close();
    
             //保存Workbook方式二: 保存到内存流中
             var stream = new MemoryStream();
             workbook.Write(stream);
    
     
             //文件下载
             Response.Clear();
             Response.Charset = "utf-8";
             Response.Buffer = true;
             this.EnableViewState = false;
             Response.ContentEncoding = System.Text.Encoding.UTF8;
     
             Response.ContentType = "application/vnd.ms-excel";
             Response.AddHeader("Content-Disposition", "attachment;filename="+ExcelName);
    
             string filename =Server.MapPath("file/" + ExcelName);//通过服务器文件下载
             Response.WriteFile(filename);
             Response.BinaryWrite(StreamToBytes(stream));//通过内存流下载,StreamToBytes为Stream转byte[] 方法 可查看我其他随笔有
             Response.Flush();   Response.Close(); 
             Response.End();
         }
    

      

     
  • 相关阅读:
    泛型编程 --迭代器
    cpp输入输出加速
    算法训练 加法运算(指针的一个测试)
    蓝桥杯-基础练习-字母图形
    蓝桥杯-基础练习-特殊回文数
    win10下稍微美观下Git
    mysql8.0以上版本注册驱动并建立数据库的连接公共代码
    idea使用的一些问题解决记录
    单链表逆转(递归指针实现)
    increment/decrement/dereference操作符
  • 原文地址:https://www.cnblogs.com/shengwei/p/4478591.html
Copyright © 2011-2022 走看看