天天看點

C#資料導出到Excel(或Word)源代碼大全(一)

一、DataSet資料集内資料轉化為Excel

  1. // 作用:把DataSet資料集内資料轉化為Excel、Word檔案
  2. // 描述:這些關于Excel、Word的導出方法,基本可以實作日常須要,其中有些方法可以把資料導出後
  3. //        生成Xml格式,再導入資料庫!有些屏蔽内容沒有去掉,保留下來友善學習參考用之。   
  4. // 備注:請引用Office相應COM元件,導出Excel對象的一個方法要調用其中的一些方法和屬性。
  5. public void DataSetToExcel(DataSet ds,string FileName)
  6. {
  7.    try
  8.     {
  9.       //Web頁面定義
  10.       //System.Web.UI.Page mypage=new System.Web.UI.Page();
  11.        HttpResponse resp;
  12.        resp=HttpContext.Current.Response;
  13.        resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
  14.        resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
  15.        resp.ContentType="application/ms-excel";
  16.       //變量定義
  17.       string colHeaders=null;
  18.       string Is_item=null;
  19.       //顯示格式定義
  20.       //檔案流操作定義
  21.       //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
  22.       //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
  23.        StringWriter sfw=new StringWriter();
  24.       //定義表對象與行對象,同時用DataSet對其值進行初始化
  25.        System.Data.DataTable dt=ds.Tables[0];
  26.        DataRow[] myRow=dt.Select();
  27.       int i=0;
  28.       int cl=dt.Columns.Count;
  29.       //取得資料表各列标題,各标題之間以/t分割,最後一個列标題後加回車符
  30.       for(i=0;i<cl;i++)
  31.        {
  32.          //if(i==(cl-1))   //最後一列,加/n
  33.          // colHeaders+=dt.Columns[i].Caption.ToString();
  34.          //else
  35.           colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
  36.        }
  37.        sfw.WriteLine(colHeaders);
  38.       //sw.WriteLine(colHeaders);
  39.       //逐行處理資料
  40.       foreach(DataRow row in myRow)
  41.        {
  42.          //目前資料寫入
  43.          for(i=0;i<cl;i++)
  44.           {
  45.           //if(i==(cl-1))
  46.           //    Is_item+=row[i].ToString()+"/n";
  47.           //else
  48.            Is_item+=row[i].ToString()+"/t";
  49.           }
  50.           sfw.WriteLine(Is_item);
  51.          //sw.WriteLine(Is_item);
  52.           Is_item=null;
  53.        }
  54.        resp.Write(sfw);
  55.       //resp.Clear();
  56.        resp.End();
  57.     }
  58.    catch(Exception e)
  59.     {
  60.       throw e;
  61.     }
  62. }

二、DataSet資料集内資料轉化為Excel檔案(2)

  1. /// <summary>
  2. /// ExportFiles 的摘要說明。
  3. /// 作用:把DataSet資料集内資料轉化為Excel檔案
  4. /// 描述:導出Excel檔案   
  5. /// 備注:請引用Office相應COM元件,導出Excel對象的一個方法要調用其中的一些方法和屬性。
  6. /// </summary>
  7. public class ExportFiles
  8. {
  9.     private string filePath = "";
  10.     public ExportFiles(string excel_path)
  11.      {
  12.         //
  13.         // TODO: 在此處添加構造函數邏輯
  14.         //
  15.          filePath = excel_path;
  16.      }
  17.     /// <summary>
  18.     /// 将指定的Dataset導出到Excel檔案
  19.     /// </summary>
  20.     /// <param name="dt"></param>
  21.     /// <returns></returns>
  22.     public bool ExportToExcel(System.Data.DataSet ds, string ReportName)
  23.      {
  24.         if (ds.Tables[0].Rows.Count == 0)
  25.          {
  26.              MessageBox.Show("資料集為空");
  27.          }
  28.          Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
  29.          Workbook xlbook = xlapp.Workbooks.Add(true);
  30.          Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
  31.          Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
  32.          range.MergeCells = true;
  33.          xlapp.ActiveCell.FormulaR1C1 = ReportName;
  34.          xlapp.ActiveCell.Font.Size = 20;
  35.          xlapp.ActiveCell.Font.Bold = true;
  36.          xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
  37.         int colIndex = 0;
  38.         int RowIndex = 2;
  39.         //開始寫入每列的标題
  40.         foreach (DataColumn dc in ds.Tables[0].Columns)
  41.          {
  42.              colIndex++;
  43.              xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
  44.          }
  45.         //開始寫入内容
  46.         int RowCount = ds.Tables[0].Rows.Count;//行數
  47.         for (int i = 0; i < RowCount; i++)
  48.          {
  49.              RowIndex++;
  50.             int ColCount = ds.Tables[0].Columns.Count;//列數
  51.             for (colIndex = 1; colIndex <= ColCount; colIndex++)
  52.              {
  53.                  xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i, colIndex - 1];
  54.                  xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;
  55.              }
  56.          }
  57.          xlbook.Saved = true;
  58.          xlbook.SaveCopyAs(filePath);
  59.          xlapp.Quit();
  60.          GC.Collect();
  61.         return true;
  62.      }
  63.     public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName)
  64.      {
  65.         if (ds.Tables[0].Rows.Count == 0)
  66.          {
  67.              MessageBox.Show("資料集為空");
  68.          }
  69.         string FileName = filePath;
  70.         //System.Data.DataTable dt = new System.Data.DataTable();
  71.          FileStream objFileStream;
  72.          StreamWriter objStreamWriter;
  73.         string strLine = "";
  74.          objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
  75.          objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
  76.          strLine = ReportName;
  77.          objStreamWriter.WriteLine(strLine);
  78.          strLine = "";
  79.         for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
  80.          {
  81.              strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + "           " + Convert.ToChar(9);
  82.          }
  83.          objStreamWriter.WriteLine(strLine);
  84.          strLine = "";
  85.         for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
  86.          {
  87.              strLine = strLine + (i + 1) + Convert.ToChar(9);
  88.             for (int j = 1; j < ds.Tables[0].Columns.Count; j++)
  89.              {
  90.                  strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9);
  91.              }
  92.              objStreamWriter.WriteLine(strLine);
  93.              strLine = "";
  94.          }
  95.          objStreamWriter.Close();
  96.          objFileStream.Close();
  97.         //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
  98.         //Workbook xlbook = xlapp.Workbooks.Add(true);
  99.         //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
  100.         //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
  101.         //range.EntireColumn.AutoFit();
  102.         //xlapp.Quit();
  103.         return true;
  104.      }     
  105. }

三、生成XML然後轉換成Excel方式

參考資源:http://www.codeproject.com/office/Excel_Export.asp?df=100&forumid=329437&fr=51 (源程式)

優點:

a. 服務端不用安裝Excel程式。

b. 支援一定的Excel檔案格式設定,比如字型大小、顔色、合并單元格等。

缺點:

a. 與Excel 2000不相容:由于Excel 2000不支援XML,是以以這種方法生成的Excel檔案可能在Excel2000中不相容(畢竟目前還有不少使用者的電腦裝的是Excel 2000)。

b. 可能不支援Excel檔案頁邊距的設定;不支援Excel檔案橫向、縱向的設定;不支援Excel模闆;

c. 程式設計工作量比較大;

d. 生成的檔案本質上是XML檔案,需要“另存為xls”才能變成真正的Excel檔案。

e. 性能是好是壞還不清楚,目前還沒真正在項目中用過。希望有用過此方案的朋友能介紹一下這個方案的性能。

四、導出GridView到Excel

  1. //導出GridView到Excel中的關鍵之處
  2. //用法: ToExcel(GVStaff, TextBox1.Text);
  3. public static void ToExcel(System.Web.UI.Control ctl,string FileName)
  4. {
  5.      HttpContext.Current.Response.Charset ="UTF-8";
  6.      HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
  7.      HttpContext.Current.Response.ContentType ="application/ms-excel";
  8.      HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
  9.      ctl.Page.EnableViewState =false;
  10.      System.IO.StringWriter   tw = new System.IO.StringWriter();
  11.      HtmlTextWriter hw = new HtmlTextWriter(tw);
  12.      ctl.RenderControl(hw);
  13.      HttpContext.Current.Response.Write(tw.ToString());
  14.      HttpContext.Current.Response.End();
  15. }        
  16. 必須有下面這句!否則不會通過!
  17. public override void VerifyRenderingInServerForm(Control control)
  18. {
  19.     // Confirms that an HtmlForm control is rendered for
  20. }

繼續閱讀