C#匯出分Sheet的Excel檔案69b3850b

來源:互聯網
上載者:User

 69b3850b

由於EXCEL 2003有65536行資料的限制,故在超過這個限制時須分成多個Sheet來顯示,本人通過網上部分資料加上自己的應用心得總結出以下方法,希望能為廣大工友帶來方便.

首先,如果您使用的是VS2005,則須引入Excel.dll檔案;如果您使用的是VS2003,則引入Interop.Excel.dll檔案,一般工程會自動引入.

然後,引用命名空間:using Excel;

最後添加方法:

   /// <summary>
   /// 將傳入的DataSet資料匯出至Excel檔案
   /// </summary>
   /// <param name="ctl">DataGrid</param>
   public static void DataSet2Excel(DataSet ds)
   {
    int maxRow=ds.Tables[0].Rows.Count;
    string fileName=DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls";//設定匯出檔案的名稱

    DataView dv=new DataView(ds.Tables[0]);//將DataSet轉換成DataView
    string fileURL=string.Empty;
    //調用方法將檔案寫入伺服器,並擷取全部路徑
    fileURL=DataView2ExcelBySheet(dv,fileName);
    //擷取路徑後從伺服器下載檔案至本地
    HttpContext curContext=System.Web.HttpContext.Current;
    curContext.Response.ContentType="application/vnd.ms-excel";
    curContext.Response.ContentEncoding=System.Text.Encoding.Default;
    curContext.Response.AppendHeader("Content-Disposition", ("attachment;filename=" + fileName));
    curContext.Response.Charset = "";

    curContext.Response.WriteFile(fileURL);
    curContext.Response.Flush();
    curContext.Response.End();
   }

   /// <summary>
   /// 分Sheet匯出Excel檔案
   /// </summary>
   /// <param name="dv">需匯出的DataView</param>
   /// <returns>匯出檔案的路徑</returns>
   private static string DataView2ExcelBySheet(DataView dv,string fileName)
   {
    int sheetRows=65535;//設定Sheet的行數,此為最大上限,本來是65536,因表頭要佔去一行
    int sheetCount = (dv.Table.Rows.Count - 1) / sheetRows + 1;//計算Sheet數

    GC.Collect();//記憶體回收

    Application excel;
    _Workbook xBk;
    _Worksheet xSt=null;
    excel = new ApplicationClass();
    xBk = excel.Workbooks.Add(true);
   
    //定義迴圈中要使用的變數
    int dvRowStart;
    int dvRowEnd;
    int rowIndex = 0;
    int colIndex = 0;
    //對全部Sheet進行操作
    for (int sheetIndex = 0; sheetIndex < sheetCount; sheetIndex++)
    {
     //初始化Sheet中的變數
     rowIndex = 1;
     colIndex = 1;
     //計算起始行
     dvRowStart = sheetIndex * sheetRows;
     dvRowEnd = dvRowStart + sheetRows-1;
     if (dvRowEnd > dv.Table.Rows.Count-1)
     {
      dvRowEnd = dv.Table.Rows.Count - 1;
     }
     //建立一個Sheet
     if (null == xSt)
     {
      xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, Type.Missing, 1, Type.Missing);
     }
     else
     {
      xSt = (_Worksheet)xBk.Worksheets.Add(Type.Missing, xSt, 1, Type.Missing);
     }
     //設定Sheet的名稱
     xSt.Name = "Expdata";
     if (sheetCount > 1)
     {
      xSt.Name += ((int)(sheetIndex + 1)).ToString();
     }
     //取得標題
     foreach (DataColumn col in dv.Table.Columns)
     {
      //設定標題格式
      xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = XlVAlign.xlVAlignCenter; //設定標題置中對齊
      xSt.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).Font.Bold = true;//設定標題為粗體
      //填值,並進行下一列
      excel.Cells[rowIndex, colIndex++] = col.ColumnName;
     }
     //取得表格中數量
     int drvIndex;
     for(drvIndex=dvRowStart;drvIndex<=dvRowEnd;drvIndex++)
     {
      DataRowView row=dv[drvIndex];
      //新起一行,目前的儲存格移至行首
      rowIndex++;
      colIndex = 1;
      foreach (DataColumn col in dv.Table.Columns)
      {
       if (col.DataType == System.Type.GetType("System.DateTime"))
       {
        excel.Cells[rowIndex, colIndex] = (Convert.ToDateTime(row[col.ColumnName].ToString())).ToString("yyyy-MM-dd");
       }
       else if (col.DataType == System.Type.GetType("System.String"))
       {
        excel.Cells[rowIndex, colIndex] = "'" + row[col.ColumnName].ToString();
       }
       else
       {
        excel.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
       }
       colIndex++;
      }
     }
     //使用最佳寬度
     Range allDataWithTitleRange = xSt.get_Range(excel.Cells[1, 1], excel.Cells[rowIndex, colIndex-1]);
     allDataWithTitleRange.Select();
     allDataWithTitleRange.Columns.AutoFit();
     allDataWithTitleRange.Borders.LineStyle = 1;//將匯出Excel加上邊框
    }
    //設定匯出檔案在伺服器上的檔案夾
    string exportDir="~/ExcelFile/";//注意:該檔案夾您須事先在伺服器上建好才行
    //設定檔案在伺服器上的路徑
    string absFileName = HttpContext.Current.Server.MapPath(System.IO.Path.Combine(exportDir,fileName));
    xBk.SaveCopyAs(absFileName);
    xBk.Close(false, null, null);
    excel.Quit();

    System.Runtime.InteropServices.Marshal.ReleaseComObject(xBk);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(xSt);

    xBk = null;
    excel = null;
    xSt = null;
    GC.Collect();
    //返回寫入伺服器Excel檔案的路徑
    return absFileName;
   }

說明:如果您需要將匯出檔案儲存到伺服器,則只需採用DataView2ExcelBySheet方法即可,且不需返迴路徑,直接在伺服器的該路徑下即可找到檔案.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.