原帖地址:http://topic.csdn.net/u/20110724/01/975fa99f-6656-4ea8-827c-b62104eb01da.html
技术要点:1.使用的是StreamWriter sw = new StreamWriter(path, false,Encoding.GetEncoding("gb2312"));最终生成文件
2.使用 StringBuilder sb = new StringBuilder();类把查询出来的数据组合为一句超长字符串一次性插入到excel中,
sb.Append(ds.Tables[0].Columns[k].ColumnName.ToString() + "\t");
注意,可不能漏了"\t" 这个是非常重要的! 因为c# "\t"就等于 键盘上的Tab [朋友们可以试试:打开新的txt然后输入1按Tab,输入2按Tab,输入3按Tab保存,然后打开excel文件 把刚刚保存的txt文件拉进去打开你就发现原来。这样写的话1 2 3 会分别在每个单元格上的了。所以上面才使用 "\t"连起来数据库出来的那堆数据,这样一次性导进去,他们就会按照每个单元格来填充!]
需要引用:
using System.Threading;
using System.IO;
方法如下:
-
C# code
-
private void button1_Click(object sender, EventArgs e) { saveFileDialog1.Title = "保存的excel文件"; saveFileDialog1.InitialDirectory = "c:\\"; saveFileDialog1.Filter = "Excel97-2003 (*.xls)|*.xls|All Files (*.*)|*.*"; saveFileDialog1.ShowDialog(); if (saveFileDialog1.FileName == "" || saveFileDialog1.FileName == null) { MessageBox.Show("文件名不能为空!"); return; } string path = saveFileDialog1.FileName; string constr = "Data Source=.;Initial Catalog=Exhibition;User ID=sa;Password="; string sql = GetStrSql(); DataSet ds=new DataSet(); using (SqlConnection con = new SqlConnection(constr)) { SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(ds); } if (ds == null) { MessageBox.Show("数据获取有误!"); return; } WriteExcel(ds, path); } public void WriteExcel(DataSet ds, string path) { try { long totalCount = ds.Tables[0].Rows.Count; lblTip.Text = "共有" + totalCount + "条数据。"; Thread.Sleep(1000); long rowRead = 0; float percent = 0; StreamWriter sw = new StreamWriter(path, false,Encoding.GetEncoding("gb2312")); StringBuilder sb = new StringBuilder(); for (int k = 0; k < ds.Tables[0].Columns.Count; k++) { sb.Append(ds.Tables[0].Columns[k].ColumnName.ToString() + "\t"); } sb.Append(Environment.NewLine); for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { rowRead++; percent = ((float)(100 * rowRead)) / totalCount; Pbar.Maximum = (int)totalCount; Pbar.Value = (int)rowRead; lblTip.Text = "正在写入[" + percent.ToString("0.00") + "%]...的数据"; System.Windows.Forms.Application.DoEvents(); for (int j = 0; j < ds.Tables[0].Columns.Count; j++) { sb.Append(ds.Tables[0].Rows[i][j].ToString() + "\t"); } sb.Append(Environment.NewLine); } sw.Write(sb.ToString()); sw.Flush(); sw.Close(); MessageBox.Show("已经生成指定Excel文件!"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public string GetStrSql() { string strSql = "select * from table"; return strSql; }