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();
}
}
【注:在VS.Net中运行是要添加Excel.dll组件的,Excel组件VS.Net本身是没有的,下面是生成Excel.dll的方法。】
1.要保证机器本身要安装OFFICE.
2.把[C:\Program Files\Microsoft Office\Office:默认安装路径]下的EXCEL9.OLB文件拷贝到[C:\Visual Studio.Net\SDK\v1.1\Bin:VS.Net安装路径]路径下。
3.打开Visual Studio .Net2003命令提示,运行TlbImp Excel9.olb Excel.dll ,就会在[C:\Visual Studio.Net\SDK\v1.1\Bin]下生成Excel.dll组件。
4.在项目中添加Excel.dll引用就OK了。
在你的计算机中找到TlbImp和Excel9.olb,将他们复制到一个文件夹中,在DOS窗口中执行 TlbImp Excel9.olb,这时会产生以下三个文件:Excel.dll、Office.dll和VBIDE.dll。"
============================================
//连接excel数据源
string filename = this.openFileDialog2.FileName;
string filePath = this.openFileDialog1.FileName;
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+ filePath + ";Extended Properties=\"Excel 8.0;\"");
conn.Open();
//建立Excel应用(写Excel Sheet之前)
Microsoft.Office.Interop.Excel.ApplicationClass oExcel;
oExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
oExcel.UserControl = false;
Microsoft.Office.Interop.Excel.WorkbookClass wb = (Microsoft.Office.Interop.Excel.WorkbookClass)oExcel.Workbooks.Add(System.Reflection.Missing.Value);
//新建一个Sheet,新建后会默认处于焦点状态
wb.Worksheets.Add(Missing.Value, Missing.Value, 1, Missing.Value);
//写单元格示例
oExcel.Cells[1, 1] = "第一列";
oExcel.Cells[1, 2] = "第二列";
oExcel.Cells[1, 3] = "第三列";
//保存工作簿
wb.Saved = true;
//生成文件,释放资源
oExcel.ActiveWorkbook.SaveCopyAs(filename);
oExcel.Quit();
System.GC.Collect();