一、DataSet資料集内資料轉化為Excel
- // 作用:把DataSet資料集内資料轉化為Excel、Word檔案
- // 描述:這些關于Excel、Word的導出方法,基本可以實作日常須要,其中有些方法可以把資料導出後
- // 生成Xml格式,再導入資料庫!有些屏蔽内容沒有去掉,保留下來友善學習參考用之。
- // 備注:請引用Office相應COM元件,導出Excel對象的一個方法要調用其中的一些方法和屬性。
- public void DataSetToExcel(DataSet ds,string FileName)
- {
- try
- {
- //Web頁面定義
- //System.Web.UI.Page mypage=new System.Web.UI.Page();
- HttpResponse resp;
- resp=HttpContext.Current.Response;
- resp.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
- resp.AppendHeader("Content-disposition","attachment;filename="+FileName+".xls");
- resp.ContentType="application/ms-excel";
- //變量定義
- string colHeaders=null;
- string Is_item=null;
- //顯示格式定義
- //檔案流操作定義
- //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
- //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
- StringWriter sfw=new StringWriter();
- //定義表對象與行對象,同時用DataSet對其值進行初始化
- System.Data.DataTable dt=ds.Tables[0];
- DataRow[] myRow=dt.Select();
- int i=0;
- int cl=dt.Columns.Count;
- //取得資料表各列标題,各标題之間以/t分割,最後一個列标題後加回車符
- for(i=0;i<cl;i++)
- {
- //if(i==(cl-1)) //最後一列,加/n
- // colHeaders+=dt.Columns[i].Caption.ToString();
- //else
- colHeaders+=dt.Columns[i].Caption.ToString()+"/t";
- }
- sfw.WriteLine(colHeaders);
- //sw.WriteLine(colHeaders);
- //逐行處理資料
- foreach(DataRow row in myRow)
- {
- //目前資料寫入
- for(i=0;i<cl;i++)
- {
- //if(i==(cl-1))
- // Is_item+=row[i].ToString()+"/n";
- //else
- Is_item+=row[i].ToString()+"/t";
- }
- sfw.WriteLine(Is_item);
- //sw.WriteLine(Is_item);
- Is_item=null;
- }
- resp.Write(sfw);
- //resp.Clear();
- resp.End();
- }
- catch(Exception e)
- {
- throw e;
- }
- }
二、DataSet資料集内資料轉化為Excel檔案(2)
- /// <summary>
- /// ExportFiles 的摘要說明。
- /// 作用:把DataSet資料集内資料轉化為Excel檔案
- /// 描述:導出Excel檔案
- /// 備注:請引用Office相應COM元件,導出Excel對象的一個方法要調用其中的一些方法和屬性。
- /// </summary>
- public class ExportFiles
- {
- private string filePath = "";
- public ExportFiles(string excel_path)
- {
- //
- // TODO: 在此處添加構造函數邏輯
- //
- filePath = excel_path;
- }
- /// <summary>
- /// 将指定的Dataset導出到Excel檔案
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public bool ExportToExcel(System.Data.DataSet ds, string ReportName)
- {
- if (ds.Tables[0].Rows.Count == 0)
- {
- MessageBox.Show("資料集為空");
- }
- Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
- Workbook xlbook = xlapp.Workbooks.Add(true);
- Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
- Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
- range.MergeCells = true;
- xlapp.ActiveCell.FormulaR1C1 = ReportName;
- xlapp.ActiveCell.Font.Size = 20;
- xlapp.ActiveCell.Font.Bold = true;
- xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
- int colIndex = 0;
- int RowIndex = 2;
- //開始寫入每列的标題
- foreach (DataColumn dc in ds.Tables[0].Columns)
- {
- colIndex++;
- xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
- }
- //開始寫入内容
- int RowCount = ds.Tables[0].Rows.Count;//行數
- for (int i = 0; i < RowCount; i++)
- {
- RowIndex++;
- int ColCount = ds.Tables[0].Columns.Count;//列數
- for (colIndex = 1; colIndex <= ColCount; colIndex++)
- {
- xlsheet.Cells[RowIndex, colIndex] = ds.Tables[0].Rows[i][colIndex - 1];//dg[i, colIndex - 1];
- xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;
- }
- }
- xlbook.Saved = true;
- xlbook.SaveCopyAs(filePath);
- xlapp.Quit();
- GC.Collect();
- return true;
- }
- public bool ExportToExcelOF(System.Data.DataSet ds, string ReportName)
- {
- if (ds.Tables[0].Rows.Count == 0)
- {
- MessageBox.Show("資料集為空");
- }
- string FileName = filePath;
- //System.Data.DataTable dt = new System.Data.DataTable();
- FileStream objFileStream;
- StreamWriter objStreamWriter;
- string strLine = "";
- objFileStream = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
- objStreamWriter = new StreamWriter(objFileStream, System.Text.Encoding.Unicode);
- strLine = ReportName;
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
- {
- strLine = strLine + ds.Tables[0].Columns[i].ColumnName.ToString() + " " + Convert.ToChar(9);
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
- {
- strLine = strLine + (i + 1) + Convert.ToChar(9);
- for (int j = 1; j < ds.Tables[0].Columns.Count; j++)
- {
- strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9);
- }
- objStreamWriter.WriteLine(strLine);
- strLine = "";
- }
- objStreamWriter.Close();
- objFileStream.Close();
- //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
- //Workbook xlbook = xlapp.Workbooks.Add(true);
- //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
- //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
- //range.EntireColumn.AutoFit();
- //xlapp.Quit();
- return true;
- }
- }
三、生成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
- //導出GridView到Excel中的關鍵之處
- //用法: ToExcel(GVStaff, TextBox1.Text);
- public static void ToExcel(System.Web.UI.Control ctl,string FileName)
- {
- HttpContext.Current.Response.Charset ="UTF-8";
- HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
- HttpContext.Current.Response.ContentType ="application/ms-excel";
- HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
- ctl.Page.EnableViewState =false;
- System.IO.StringWriter tw = new System.IO.StringWriter();
- HtmlTextWriter hw = new HtmlTextWriter(tw);
- ctl.RenderControl(hw);
- HttpContext.Current.Response.Write(tw.ToString());
- HttpContext.Current.Response.End();
- }
- 必須有下面這句!否則不會通過!
- public override void VerifyRenderingInServerForm(Control control)
- {
- // Confirms that an HtmlForm control is rendered for
- }