因为朋友是做实施的,他工作需要要导出大量数据岛Excel,但又因为懒,不想手动去操作,所以请我帮忙,我写了一个小程序,在这里给大家分享下。
界面很简单,随意拉了几个控件:
技术要点:1.创建文件流,用于写最终的文件StreamWriter sw = new StreamWriter(fileName, false,Encoding.GetEncoding("gb2312"));
2.使用 StringBuilder类把数据组合为长字符串插入到excel文件中,
sb.Append(dt.rows[i][j].ToString() + " ");
注 意,可不能漏了" " 这个是非常重要的! 因为c# " "就等于 键盘上的Tab [朋友们可以试试:打开新的txt然后输入1按Tab,输入2按Tab,输入3按Tab保存,然后打开excel文件 把刚刚保存的txt文件拉进去打开你就发现原来。这样写的话1 2 3 会分别在每个单元格上的了。所以上面才使用 " "连起来数据库出来的那堆数据,这样一次性导进去,他们就会按照每个单元格来填充!废话不多说了,直接上code。
后台代码:
using Microsoft.Reporting.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ReportExcel { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } string saveAddr = string.Empty; private void btnDoing_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); string tableName = txtTableName.Text.Trim(); int totalCount = Convert.ToInt32(txtCount.Text); string sortFiled = txtSortFiled.Text.Trim(); int startIndex = Convert.ToInt32(txtStartIndex.Text.Trim()); using (SqlConnection conn = new SqlConnection("Data Source=.;User ID=sa;Password=123456;Initial Catalog=MakeSun_B2C;")) { conn.Open(); string sql = string.Format("select top {0} * from {1} where {2} >{3} order by {4} ", totalCount, tableName, sortFiled, startIndex, sortFiled); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataAdapter ada = new SqlDataAdapter(cmd); ada.Fill(dt); } string maxNum = dt.Rows[dt.Rows.Count - 1][sortFiled].ToString(); WriteExcel(dt, saveAddr, maxNum); } void WriteExcel(DataTable ds, string path, string maxNum) { try { StreamWriter sw = new StreamWriter(path, false, Encoding.GetEncoding("gb2312")); StringBuilder sb = new StringBuilder(); for (int k = 0; k < ds.Columns.Count; k++) { sb.Append(ds.Columns[k].ColumnName.ToString() + " "); } sb.Append(Environment.NewLine); int rowCount = ds.Rows.Count; for (int i = 0; i < rowCount; i++) { progressBar1.Value = 100 * (i + 1) / rowCount; progressBar1.Refresh(); for (int j = 0; j < ds.Columns.Count; j++) { sb.Append(ds.Rows[i][j].ToString() + " "); } sb.Append(Environment.NewLine);//每写一行数据后换行 } sw.Write(sb.ToString()); sw.Flush(); sw.Close();//释放资源 progressBar1.Value = 100; MessageBox.Show("已经生成指定Excel文件! 最大的排序字段为 " + maxNum + ",记得下次从" + maxNum + "开始导出。"); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button1_Click(object sender, EventArgs e) { saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*"; DialogResult dia = saveFileDialog1.ShowDialog(); if (dia == DialogResult.OK) { saveAddr = saveFileDialog1.FileName; textBox1.Text = saveAddr; } } } }