เขียน MS Excel ไฟล์ ด้วย C# (2009-12-24)
เอาละ เริ่มต้นในการเขียนไฟล์ MS Excel
1. ไปที่ File > New > Project
2. สำหรับตัวอย่างเราเลือกไฟล์ไปที่ Visual C# > Windows > Console Application
3.ทำการ Add Reference > COM > Microsoft Excel 12.0 Object Library
โดย Microsoft Excel 12.0 Object Library จะเป็นของ MS Office 2007
แต่ถ้าเป็น Microsoft Excel 11.0 Object Library จะเป็นของ MS Office 2003
ซึ่งถ้าท่านไม่เจอ อาจเป็นเพราะท่านไม่ได้ลง MS Office ที่เครื่องของท่าน

4 จากนั้นใส่ code ตามไฟล์ข้างล่างเลยครับ
System.Threading.Thread.CurrentThread.CurrentCulture=System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
Microsoft.Office.Interop.Excel.ApplicationClass excelSheet=new Microsoft.Office.Interop.Excel.ApplicationClass();
excelSheet.Application.Workbooks.Add(true);
//Create header
excelSheet.Cells[1, 1] = "ID";
excelSheet.Cells[1, 2] = "NAME";
excelSheet.Cells[1, 3] = "CREATE DATE";
//Loop for export locCollection to excel file
for (int i = 0; i < customerCollection.Count - 1; i++)
{
Customer customer = (Customer)customerCollection[i];
excelSheet.Cells[i + 2, 1] = customer.Id.ToString();
excelSheet.Cells[i + 2, 2] = customer.Name;
excelSheet.Cells[i + 2, 3] = customer.CreateTime.ToString();
}
excelSheet.Visible = true;
excelSheet.ActiveWorkbook.SaveCopyAs(fileName);
excelSheet.ActiveWorkbook.Saved = true;
excelSheet.Quit();
ลองเอาไปประยุกต์ใช้ดูแล้วกันนะครับ เดี๋ยวตอนแต่ไปผมจะพูดถึงการเขียนไฟล์ Excel บน Web Application ครับ
Download : WriteExcelFile.zip
|