[.NET-Winform]使用datagrid导出数据到Excel |
麦林 发表于 2007/8/31 10:03:21 | 部分可执行代码: private void button1_Click(object sender, EventArgs e) { Form1 seven = new Form1(); DataSet dsSeven = seven.getAll(); ExportData(dsSeven); }
public DataSet getAll() { string connString = "server= .; uid = sa ; pwd = 123;database = Manager"; SqlConnection con = new SqlConnection(connString); con.Open(); SqlDataAdapter da = new SqlDataAdapter("select * from CustomerInformation", con); DataSet ds = new DataSet(); da.Fill(ds); return ds; con.Close(); }
public void ExportData(DataSet dsIn) { if (dsIn.Tables.Count != 0) { //建立一个Excel文件(程序运行的当前路径,当前时间为文件名) string tempFileName = System.DateTime.Now.ToString("yyyyMMddhhmmssfff"); object filename = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + tempFileName + ".xls"; object nothing = System.Reflection.Missing.Value;
Excel.Application myExcel = new Excel.ApplicationClass(); myExcel.Application.Workbooks.Add(nothing);
try { int totalCount = 0;
int row = dsIn.Tables[0].Rows.Count; int column = dsIn.Tables[0].Columns.Count;
for (int i = 0; i < column; i++) { myExcel.Cells[totalCount + 1, 1 + i] = dsIn.Tables[0].Columns[i].ColumnName; }
for (int i = 0; i < row; i++) { for (int j = 0; j < column; j++) { myExcel.Cells[totalCount + 2 + i, 1 + j] = dsIn.Tables[0].Rows[i][j].ToString(); } }
try { myExcel.ActiveWorkbook.SaveAs(filename, nothing, nothing, nothing, nothing, nothing, XlSaveAsAccessMode.xlExclusive, nothing, nothing, nothing, nothing,nothing); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); return; } myExcel.Visible = true; } catch (Exception ex) { MessageBox.Show(ex.Message); } } else { MessageBox.Show("no Data"); } }
|
|
|

.: 公告
|
« | October 2025 | » | 日 | 一 | 二 | 三 | 四 | 五 | 六 | | | | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | | |
|
.: 我的分类(专题)
|

.: 最新日志
.: 最新回复
|

blog名称:栗色?蓝色? 日志总数:449 评论数量:201 留言数量:37 访问次数:2265640 建立时间:2006年5月16日 |
|

.: 留言板
|

.: 链接
|

|