数据导出到Excel(或Word)源代码大全
在日常工作中,大家都习惯Office作为办公软件,因此,在开发软件的时,常常会有把数据导出到Excel等Office软件的需求。在此,收集一些常用的导出文件的源程序,希望给大家带来方便。(不断更新)
一、DataSet数据集内数据转化为Excel
1. // 作用:把DataSet数据集内数据转化为Excel、Word文件
2. // 描述:这些关于Excel、Word的导出方法,基本可以实现日常须要,其中有些方法可以把数据导出后
3. // 生成Xml格式,再导入数据库!有些屏蔽内容没有去掉,保留下来方便学习参考用之。
4. // 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
5. public void DataSetToExcel(DataSet ds,string
6. {
7. try
8. {
9. //Web页面定义
10. //System.Web.UI.Page mypage=new System.Web.UI.Page();
11.
12. HttpResponse resp;
13. resp=HttpContext.Current.Response;
14. "GB2312");
15. "Content-disposition","attachment;filename="+FileName+".xls");
16. "application/ms-excel";
17.
18. //变量定义
19. string colHeaders=null;
20. string Is_item=null;
21.
22. //显示格式定义
23.
24.
25. //文件流操作定义
26. //FileStream fs=new FileStream(FileName,FileMode.Create,FileAccess.Write);
27. //StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
28.
29. new
30. //定义表对象与行对象,同时用DataSet对其值进行初始化
31. System.Data.DataTable dt=ds.Tables[0];
32. DataRow[] myRow=dt.Select();
33. int
34. int
35.
36. //取得数据表各列标题,各标题之间以/t分割,最后一个列标题后加回车符
37. for(i=0;i<cl;i++)
38. {
39. //if(i==(cl-1)) //最后一列,加/n
40. // colHeaders+=dt.Columns[i].Caption.ToString();
41. //else
42. "/t";
43. }
44. sfw.WriteLine(colHeaders);
45. //sw.WriteLine(colHeaders);
46.
47. //逐行处理数据
48. foreach(DataRow row in
49. {
50. //当前数据写入
51. for(i=0;i<cl;i++)
52. {
53. //if(i==(cl-1))
54. // Is_item+=row[i].ToString()+"/n";
55. //else
56. "/t";
57. }
58. sfw.WriteLine(Is_item);
59. //sw.WriteLine(Is_item);
60. null;
61. }
62. resp.Write(sfw);
63. //resp.Clear();
64. resp.End();
65. }
66. catch(Exception e)
67. {
68. throw
69. }
70. }
二、DataSet数据集内数据转化为Excel文件(2)
1. /// <summary>
2. /// ExportFiles 的摘要说明。
3. /// 作用:把DataSet数据集内数据转化为Excel文件
4. /// 描述:导出Excel文件
5. /// 备注:请引用Office相应COM组件,导出Excel对象的一个方法要调用其中的一些方法和属性。
6. /// </summary>
7. public class
8. {
9. private string filePath = "";
10. public ExportFiles(string
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
23. {
24. if
25. {
26. "数据集为空");
27. }
28. new
29. 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. true;
33. xlapp.ActiveCell.FormulaR1C1 = ReportName;
34. xlapp.ActiveCell.Font.Size = 20;
35. true;
36. xlapp.ActiveCell.HorizontalAlignment = Microsoft.Office.Interop.Excel.Constants.xlCenter;
37. int
38. int
39. //开始写入每列的标题
40. foreach (DataColumn dc in
41. {
42. colIndex++;
43. xlsheet.Cells[RowIndex, colIndex] = dc.Caption;
44. }
45. //开始写入内容
46. int RowCount = ds.Tables[0].Rows.Count;//行数
47. for (int
48. {
49. RowIndex++;
50. int ColCount = ds.Tables[0].Columns.Count;//列数
51. for
52. {
53. //dg[i, colIndex - 1];
54. xlsheet.Cells.ColumnWidth = ds.Tables[0].Rows[i][colIndex - 1].ToString().Length;
55. }
56. }
57.
58. true;
59. xlbook.SaveCopyAs(filePath);
60. xlapp.Quit();
61. GC.Collect();
62. return true;
63. }
64.
65. public bool ExportToExcelOF(System.Data.DataSet ds, string
66. {
67. if
68. {
69. "数据集为空");
70. }
71. string
72.
73. //System.Data.DataTable dt = new System.Data.DataTable();
74. FileStream objFileStream;
75. StreamWriter objStreamWriter;
76. string strLine = "";
77. new
78. new
79.
80. strLine = ReportName;
81. objStreamWriter.WriteLine(strLine);
82. "";
83.
84. for (int
85. {
86. " "
87. }
88. objStreamWriter.WriteLine(strLine);
89. "";
90.
91. for (int
92. {
93. strLine = strLine + (i + 1) + Convert.ToChar(9);
94. for (int
95. {
96. strLine = strLine + ds.Tables[0].Rows[i][j].ToString() + Convert.ToChar(9);
97. }
98. objStreamWriter.WriteLine(strLine);
99. "";
100. }
101. objStreamWriter.Close();
102. objFileStream.Close();
103.
104. //Microsoft.Office.Interop.Excel._Application xlapp = new ApplicationClass();
105. //Workbook xlbook = xlapp.Workbooks.Add(true);
106. //Worksheet xlsheet = (Worksheet)xlbook.Worksheets[1];
107. //Range range = xlsheet.get_Range(xlapp.Cells[1, 1], xlapp.Cells[1, ds.Tables[0].Columns.Count]);
108. //range.EntireColumn.AutoFit();
109. //xlapp.Quit();
110. return true;
111. }
112. }
三、生成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.
4. public static void ToExcel(System.Web.UI.Control ctl,string
5. {
6. "UTF-8";
7. HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
8. "application/ms-excel";
9. "Content-Disposition","attachment;filename="+""+FileName+".xls");
10. false;
11. new
12. new
13. ctl.RenderControl(hw);
14. HttpContext.Current.Response.Write(tw.ToString());
15. HttpContext.Current.Response.End();
16. }
17.
18. 必须有下面这句!否则不会通过!
19. public override void
20. {
21. // Confirms that an HtmlForm control is rendered for
22. }
五、DataTable导出到Excel
1. using
2. using
3. using
4. namespace
5. {
6. /// <summary>
7. /// DataTable导出到Excel
8. /// 整理:dongVi
9. /// </summary>
10. public class
11. {
12. private
13. {
14.
15. }
16. /// <summary>
17. /// 导出Excel
18. /// </summary>
19. /// <param name="dt">要导出的DataTable</param>
20. public static void
21. {
22. if (dt == null) return;
23.
24. new
25. if (xlApp == null)
26. {
27. // lblMsg.Text = "无法创建Excel对象,可能您的电脑未安装Excel";
28. "无法创建Excel对象,可能您的电脑未安装Excel"
29. return;
30. }
31. new
32. "Excel|*.xls";
33. "导出为Excel文件";
34. if(saveDia.ShowDialog()== System.Windows.Forms.DialogResult.OK
35. string.Empty.Equals(saveDia.FileName))
36. {
37. Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
38. Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
39. //取得sheet1
40. null;
41. long
42. long
43. float
44. string
45. //写入标题
46. for (int
47. {
48. worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
49. range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
50. //range.Interior.ColorIndex = 15;//背景颜色
51. true;//粗体
52. //居中
53. //加边框
54. null);
55. //range.ColumnWidth = 4.63;//设置列宽
56. //range.EntireColumn.AutoFit();//自动调整列宽
57. //r1.EntireRow.AutoFit();//自动调整行高
58. }
59. //写入内容
60. for (int
61. {
62. for (int
63. {
64. worksheet.Cells[r + 2, i + 1] = dt.DefaultView[r][i];
65. range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[r + 2, i + 1];
66. //字体大小
67. //加边框
68. null);
69. //自动调整列宽
70. }
71. rowRead++;
72. float)(100 * rowRead)) / totalCount;
73. System.Windows.Forms.Application.DoEvents();
74. }
75. range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideHorizontal].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
76. if
77. {
78. range.Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Weight = Microsoft.Office.Interop.Excel.XlBorderWeight.xlThin;
79. }
80. try
81. {
82. true;
83. workbook.SaveCopyAs(fileName);
84. }
85. catch
86. {
87. //lblMsg.Text = "导出文件时出错,文件可能正被打开!/n" + ex.Message;
88. "导出文件时出错,文件可能正被打开!/n"
89. return;
90. }
91.
92. workbooks.Close();
93. if (xlApp != null)
94. {
95. xlApp.Workbooks.Close();
96. xlApp.Quit();
97. int
98. System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
99. null;
100. System.GC.Collect(generation);
101. }
102. //强行销毁
103. #region 强行杀死最近打开的Excel进程
104. "EXCEL");
105. new
106. int
107. for
108. {
109. if
110. {
111. startTime = excelProc[m].StartTime;
112. killId = m;
113. }
114. }
115. if (excelProc[killId].HasExited == false)
116. {
117. excelProc[killId].Kill();
118.
119. #endregion
120. "导出成功!"
121. }
122. }
123. }
124. }
六、DataTable导出到excel(2)
1. StringWriter stringWriter = new
2. HtmlTextWriter htmlWriter = new
3. DataGrid excel = new
4. System.Web.UI.WebControls.TableItemStyle AlternatingStyle = new
5. System.Web.UI.WebControls.TableItemStyle headerStyle = new
6. System.Web.UI.WebControls.TableItemStyle itemStyle = new
7. AlternatingStyle.BackColor = System.Drawing.Color.LightGray;
8. headerStyle.BackColor =System.Drawing.Color.LightGray;
9. headerStyle.Font.Bold = true;
10. headerStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
11. itemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;;
12.
13. excel.AlternatingItemStyle.MergeWith(AlternatingStyle);
14. excel.HeaderStyle.MergeWith(headerStyle);
15. excel.ItemStyle.MergeWith(itemStyle);
16. excel.GridLines = GridLines.Both;
17. excel.HeaderStyle.Font.Bold = true;
18. excel.DataSource = dt.DefaultView;//输出DataTable的内容
19. excel.DataBind();
20. excel.RenderControl(htmlWriter);
21.
22. string filestr = "d://data//"+filePath; //filePath是文件的路径
23. int pos = filestr.LastIndexOf( "//");
24. string
25. if( !Directory.Exists( file ) )
26. {
27. Directory.CreateDirectory(file);
28. }
29. System.IO.StreamWriter sw = new
30. sw.Write(stringWriter.ToString());
31. sw.Close();
七、通过SQL直接导出到Excel数据库
1. exec master..xp_cmdshell @# bcp "SELECT au_fname, au_lname FROM pubs..authors ORDER BY au_lname" queryout c:/test.xls -c -S"soa" -U"sa" -P"sa"
注意:参数的大小写,另外这种方法写入数据的时候没有标题。
关于通过SQL读取EXCEL的方法请参见:
八、用OleDB 把 DataSet 数据导出到 Excel文件里
1. //dt为数据源(数据表)
2. //ExcelFileName 为要导出的Excle文件
3. //ModelFile为模板文件,该文件与数据源中的表一致。否则数据会导出失败。
4. //ModelFile文件里,需要有一张 与 dt.TableName 一致的表,而且字段也要一致。
5. //注明:如果不用ModelFile的话,可以用一个空白Excel文件,不过,要去掉下面创建表的注释,让OleDb自己创建一个空白表。
6. public static string TableToExcelFile(DataTable dt,string ExcelFileName,string
7. {
8. //复制一个空文件,提供写入数据用
9.
10. if(File.Exists(ExcelFileName)==false)
11. {
12. return "系统创建临时文件失败,请与系统管理员联系!";
13. }
14.
15. if(dt == null)
16. {
17. return "DataTable不能为空";
18. }
19.
20. int
21.
22. int
23. StringBuilder sb;
24. string
25.
26. if(rows == 0)
27. {
28. return "没有数据";
29. }
30.
31. new
32. "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ExcelFileName+";Extended Properties=Excel 8.0;";
33.
34. //生成创建表的脚本
35. //----sb.Append("DROP TABLE "+dt.TableName);
36.
37. /*
38. sb.Append("CREATE TABLE ");
39. sb.Append(dt.TableName + " ( ");
40. for(int i=0;i<cols;i++)
41. {
42. if(i < cols - 1)
43. sb.Append(string.Format("{0} varchar,",dt.Columns[i].ColumnName));
44. else
45. sb.Append(string.Format("{0} varchar)",dt.Columns[i].ColumnName));
46. }
47. */
48.
49. //return sb.ToString();
50.
51. new
52. new
53. objCmd.Connection = objConn;
54. //objCmd.CommandText=sb.ToString();
55.
56. try
57. {
58. objConn.Open();
59. //objCmd.ExecuteNonQuery();
60. }
61. catch(Exception e)
62. {
63. return "在Excel中创建表失败,错误信息:"
64. }
65.
66. sb.Remove(0,sb.Length);
67.
68. "INSERT INTO ");
69. " ( ");
70.
71. for(int
72. {
73. if(i < cols - 1)
74. ",");
75. else
76. ") values (");
77. }
78.
79. for(int
80. {
81. if(i < cols - 1)
82. "@" + dt.Columns[i].ColumnName + ",");
83. else
84. "@" + dt.Columns[i].ColumnName + ")");
85. }
86.
87. //建立插入动作的Command
88. objCmd.CommandText = sb.ToString();
89. OleDbParameterCollection param = objCmd.Parameters;
90.
91. for(int
92. {
93. new OleDbParameter("@"
94. }
95.
96. //遍历DataTable将数据插入新建的Excel文件中
97. foreach (DataRow row in
98. {
99. for (int
100. {
101. param[i].Value = row[i];
102. }
103.
104. objCmd.ExecuteNonQuery();
105. }
106.
107. return "数据已成功导入Excel";
108. }
109. // Trackback:
九、利用OLEDB,以excel为数据库,把dataset中的数据导入到excel文件中
1. public static void exportToExcelByDataset(string
2. {
3. string
4.
5. if(fi.Exists)
6. {
7. fi.Delete();
8. //throw new Exception("文件删除失败");
9. }
10. else
11. {
12. fi.Create();
13. }
14.
15. string mailto:sqlcon=@%22Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended ProPerties=Excel 8.0;";
16. new
17. new
18. olecmd.Connection = olecon;
19. olecmd.CommandType = CommandType.Text;
20.
21. try
22. {
23. olecon.Open();
24.
25. "./Method/ShowField");
26. int
27. "CREATE TABLE sheet1(";
28. foreach(XmlNode xnode in
29. {
30. if(ii == nodec.ChildNodes.Count - 1)
31. {
32. if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")
33. {
34. "displayname"].Value + " number)";
35. }
36. else
37. {
38. "displayname"].Value + " text)";
39. }
40. // sqlstr=sqlstr + xnode.Attributes["displayname"].Value + " text)";
41. }
42. else
43. {
44. if(xnode.Attributes["type"].Value.ToLower() == "int"||xnode.Attributes["type"].Value.ToLower() == "decimal")
45. {
46. "displayname"].Value + " number,";
47. }
48. else
49. {
50. "displayname"].Value + " text,";
51. }
52. }
53. // sqlstr =sqlstr + xnode.Attributes["displayname"].Value + " text";
54. ii++;
55. }
56. olecmd.CommandText = sqlstr;
57. olecmd.ExecuteNonQuery();
58. for(int
59. {
60. "INSERT INTO sheet1 VALUES(";
61. int
62. foreach(XmlNode inode in
63. {
64. if(jj == nodec.ChildNodes.Count-1)
65. {
66. if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
67. {
68. ")"
69. }
70. else
71. {
72. "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "')"
73. }
74. }
75. else
76. {
77. if(inode.Attributes["type"].Value.ToLower() == "int"||inode.Attributes["type"].Value.ToLower() == "decimal")
78. {
79. ","
80. }
81. else
82. {
83. "'" + isnull(ds.Tables[0].Rows[i].ItemArray[jj].ToString().Replace("'","''")) + "',"
84. }
85. }
86. jj++;
87. }
88. olecmd.CommandText = sqlstr;
89. olecmd.ExecuteNonQuery();
90. }
91. "Excel文件:" + filePath + " 导出成功!");
92. }
93. catch(Exception ex)
94. {
95. MessageBox.Show(ex.Message);
96. }
97. finally
98. {
99. olecmd.Dispose();
100. olecon.Close();
101. olecon.Dispose();
102. }
103. }
104.
105. // 判断对象为空
106. private static string isnull(string
107. {
108. if(obj.Length >0)
109. {
110. return
111. }
112. else
113. {
114. return "null";
115. }
116. }
















