使用OFFICE 的Excel 自动化服务来生成Excel文件的办法,也就是使用Excel提供的Com对象
public static void CreateExcel() { for(int i = 0 ; i<1 ; i++) { string staFile = "D:\\test\\x"; System.Reflection.Missing miss = System.Reflection.Missing.Value; Excel.ApplicationClass m_objExcel = new Excel.ApplicationClass(); m_objExcel.Visible = false; Excel.Workbooks m_objBooks = (Excel.Workbooks)m_objExcel.Workbooks; Excel.Workbook m_objBook = (Excel.Workbook)(m_objBooks.Add(miss)); Excel.Worksheet m_objSheet = (Excel.Worksheet)m_objBook.ActiveSheet; //向Excel文件中写入数据 Excel.Range er = m_objSheet.get_Range((object)"A1",System.Reflection.Missing.Value); er.Value2 = "dfadfa"; m_objBook.SaveAs(staFile+i.ToString()+".xls", miss, miss, miss, miss,miss, Excel.XlSaveAsAccessMode.xlNoChange, miss,miss,miss, miss, miss); m_objBook.Close(false, miss, miss); m_objBooks.Close(); m_objExcel.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(er); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objSheet); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBook); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objBooks); System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel); GC.Collect(); } }