DataSet導出EXCEL

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Text;
  7. using System.Windows.Forms;
  8. using System.Data.SqlClient;
  9. namespace WindowsFormsjj
  10. {
  11.     public partial class Form1 : Form
  12.     {
  13.         public Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17.         private void button1_Click(object sender, EventArgs e)
  18.         {
  19.             DataSet dss = jobset();
  20.             try
  21.             {
  22.                 Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
  23.                     myExcel.Application.Workbooks.Add(true);
  24.                     myExcel.Visible = true;
  25.                     Microsoft.Office.Interop.Excel.Range range = (Microsoft.Office.Interop.Excel.Range)myExcel.Cells[1, 1];
  26.                     int iRow = dss.Tables[0].Rows.Count;
  27.                     int iCol = dss.Tables[0].Columns.Count;
  28.                     for (int j = 0; j < iCol; j++)
  29.                     {
  30.                         myExcel.Cells[1, j + 1] = dss.Tables[0].Columns[j].ColumnName.ToString();//填充列標題
  31.                     }
  32.                     for (int i = 0; i < iRow; i++)
  33.                     {
  34.                         for (int j = 0; j < iCol; j++)
  35.                         {
  36.                             myExcel.Cells[i + 2, j + 1] = "'" + dss.Tables[0].Rows[i][j].ToString();//填充數據
  37.                         }
  38.                     }
  39.             }
  40.             catch (Exception ex)
  41.             {
  42.                 MessageBox.Show(ex.Message);
  43.             }
  44.         }
  45.         public DataSet jobset()
  46.         {
  47.             SqlConnection con = new SqlConnection("server=.;uid=sa;password=123789;database=pubs");
  48.             SqlDataAdapter da = new SqlDataAdapter("select * from titles", con);
  49.             DataSet ds = new DataSet();
  50.             da.Fill(ds);
  51.             return ds;
  52.         }
  53.     }
  54. }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章