创建Excel文件和将数据插入工作表的问题

时间:2013-04-05 05:59:11

标签: c# .net oledb

我正在尝试创建一个excel文件并将数据插入到excel文件中。 excel文件的创建不会失败,但是当我尝试将数据插入excel文件中的工作表时,我收到此错误:

Microsoft Office Access数据库引擎找不到对象'Sheet1 $'。确保对象存在,并且您正确拼写其名称和路径名称。

这是我的代码:

private void exportToExcel_Click(object sender, EventArgs e)
        {

            string excelPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\TrackITExportFile - " + DateTime.Today.ToShortDateString();
            File.Exists(excelPath);
            Microsoft.Office.Interop.Excel.Application excel = null;
            Microsoft.Office.Interop.Excel._Workbook workBook = null;
            Microsoft.Office.Interop.Excel.Sheets sheet = null;
            Microsoft.Office.Interop.Excel._Worksheet newSheet = null;

            object misValue = Missing.Value;

            excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Visible = true;
            workBook = (Microsoft.Office.Interop.Excel._Workbook)(excel.Workbooks.Add(Missing.Value));

            sheet = workBook.Sheets as Microsoft.Office.Interop.Excel.Sheets;

            newSheet = (Microsoft.Office.Interop.Excel.Worksheet)sheet.Add(sheet[1], Type.Missing, Type.Missing, Type.Missing);


            workBook.SaveAs(excelPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault,
            misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

            workBook.Close();
            excel.Quit();

            releaseObject(workBook);
            releaseObject(excel);
            releaseObject(newSheet);
            releaseObject(sheet);

            InsertData(excelPath);
        }

        public void InsertData(string fileName)
        {
            System.Data.OleDb.OleDbConnection connection;
            System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
            string sql = null;
            connection = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;ReadOnly=False;HDR=YES;\"");
            connection.Open();
            myCommand.Connection = connection;
            sql = "Insert into [Sheet1$](A1) Values ('" + ds.Tables[0].Columns[0] + "')";
            myCommand.CommandText = sql;
            myCommand.ExecuteNonQuery();
            connection.Close();
        }

我创建文件错了吗?

0 个答案:

没有答案