การ Export DataGridView to Excel File อย่างง่าย

คราวนี้จะแนะนำเทคนิค การ Export To Excel File โดยใช้  Library ของ Microsoft.Office.Interop.Excel  โดยมีแนวทางดังนี้ 
1. ต้องมี ไฟล์  Microsoft.Office.Interop.Excel.dll
อาจหา download จากอินเตอร์เน็ตได้ครับ หรือ อาจจะเอาจาก C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office14 ก็ได้ (ตัวอย่าง)
2. จากนั้นให้นำเข้า Project ของเรา 
3. เตรียมข้อมูลและ set ให้  DataGridView

DataTable table1 = new DataTable();

table1.Columns.Add("Code", typeof(string));
table1.Columns.Add("Name", typeof(string));
table1.Columns.Add("Price", typeof(string));
table1.Columns.Add("CreateDate", typeof(DateTime));

table1.Rows.Add("001", "ผงซักฟอก", 100.0, DateTime.Now);
table1.Rows.Add("002", "มาม่า", 5.5, DateTime.Now);
table1.Rows.Add("003", "น้ำตาลทราย", 30.5, DateTime.Now);
table1.Rows.Add("004", "น้ำปลาแท้", 40.0, DateTime.Now);
table1.Rows.Add("005", "กระดาษชำระ", 15.5, DateTime.Now);

dataGridView1.DataSource = table1;

4. กำหนด Event Click ให้กับปุ่ม [Export]  เขียน Code ดังนี้ 
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook ExcelBook;
Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;

int i = 0;
int j = 0;

//create object of excel
ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
          
// header
for (i = 1; i <= this.dataGridView1.Columns.Count; i++)
{
     ExcelSheet.Cells[1, i] = this.dataGridView1.Columns[i - 1].HeaderText;
 }

 // data
 for (i = 1; i <= this.dataGridView1.RowCount; i++)
 {
      for (j = 1; j <= dataGridView1.Columns.Count; j++)
      {
          ExcelSheet.Cells[i + 1, j] = dataGridView1.Rows[i - 1].Cells[j - 1].Value;
       }
  }

 ExcelApp.Visible = true;
 ExcelSheet = null;
 ExcelBook = null;
 ExcelApp = null;




5. ทดสอบโดยการกดปุ่ม [Export]


เพียงเท่านี้ครับก็สามารถ Export ข้อมูลออก Excel ได้แล้ว  สามารถนำไปประยุกต์ใช้งานต่อได้ครับ ...

2 ความคิดเห็น

กรณี price จาก dataGridView เป็น 100.00 export ออกมาแล้วได้ 100 ทำอย่างไรให้ export แสดงค่าตาม dataGridView ค่ะ

Reply

using System.Data.OleDb;

using (OpenFileDialog dialog = new OpenFileDialog() { Filter = "Excel Workbook|*.xlsx", ValidteNames = true})
{
if (dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
string ConStr = "PROVIDER=Microsoft.ACE.OLEDB.16.0;Data Source=" + path + ";Extended Properties = 'Excel 16.0;HDR=yes'";
OleDbConnection con = new OleDbConnection(ConStr);
OleDbCommand cmd = new OleDbCommand("select * from [Sheet1$]", con);
con.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
dataGridview1.DataSource = dt;
}
}

Reply

แสดงความคิดเห็น