如何使用OleDbConnection将数据插入excel

时间:2012-09-13 06:42:40

标签: c# excel

我有一个excel文件,并在其中定义了两列Date,Result。

我希望用c#插入数据。

我使用此代码:

 string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + System.AppDomain.CurrentDomain.BaseDirectory + "\\Data\\sms log.xlsx;Extended Properties=Excel 12.0;";

            OleDbConnection myConnection = new OleDbConnection(connectionString);
          if(myConnection.State==System.Data.ConnectionState.Closed)  myConnection.Open();
            OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText =string .Format( "Insert into TABLE  [Sheet1$](DateTime,Result)values('{0}','{1}')",DateTime.Now,false) ;
            myCommand.ExecuteNonQuery();
            myConnection.Close();

但我收到此错误: INSERT INTO语句中的语法错误。

2 个答案:

答案 0 :(得分:0)

试试这个语法:

myCommand.CommandText = "Insert into [Sheet1$] (id,name) values('5','e')";

答案 1 :(得分:0)

我希望你一切都好。 您可以使用EPPLus框架。 我粘贴了几个月前写的示例代码。这样,您就不需要使用Interop或担心拥有正确的OLEDB驱动程序。


string fileNameOut = @"C:\ExcelFile.xlsx";

if (File.Exists(fileNameOut))
    File.Delete(fileNameOut);       // If the file exist, then detele the file

FileInfo newFile = new FileInfo(fileNameOut);

string startdateTmp  = startdate  + " 00:00:00.000";  // "2018-05-01 00:00:00.000"
string finishdateTmp = finishdate + " 23:59:59.999";  // "2018-05-31 23:59:59.999"

string querybody = "SELECT Convert(varchar(11), [ENROLLDATE], 103) AS [ENROLLDATE], [FIRSTNAME], [LASTNAME], [GENDER] FROM [dbo].[Demographics] WHERE [EnrollDate] >= '{0}' AND [EnrollDate] <= '{1}'";
string sqlquery = string.Format(querybody, startdateTmp, finishdateTmp);


SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand command = new SqlCommand(sqlquery, sqlConnection);
command.CommandTimeout = 3600;  // Wait 3600=60 minutes

SqlDataReader reader = command.ExecuteReader();

ExcelPackage package = new ExcelPackage(newFile);
var wsDt = package.Workbook.Worksheets.Add(string.Format("All {0}:{1}", startdate, finishdate));
// Load the datatable and set the number formats...
wsDt.Cells["A1"].LoadFromDataReader(reader, true, "Demographics");

// close the reader.
reader.Close();
// close the connection with database.
sqlConnection.Close();

var headerCells = wsDt.Cells[1, 1, 1, wsDt.Tables[0].Columns.Count];
var headerFont = headerCells.Style.Font;
headerFont.Bold = true;  //headerFont.Italic = true;
//headerFont.SetFromFont(new Font("Calibri", 12, FontStyle.Bold));   //headerFont.Color.SetColor(Color.DarkBlue);

// Disable Autofilter
wsDt.Tables[0].ShowFilter = false;

// Formating numeric type or date column
wsDt.Column(1).Style.Numberformat.Format  = "dd/mm/yyyy";      // Columna: ENROLLDATE "yyyy-mm-dd" to "dd/mm/yyyy"
wsDt.Column(10).Style.Numberformat.Format = "dd/mm/yyyy";     // Columna: DOB "yyyy-mm-dd" to "dd/mm/yyyy"

// AutoFitColumns ALL columns
for (int i = 1; i <= wsDt.Tables[0].Columns.Count; i++)
    wsDt.Column(i).AutoFit();
/*
wsDt.Column(1).AutoFit();   // ENROLLDATE
wsDt.Column(2).AutoFit();   // FIRSTNAME
wsDt.Column(3).AutoFit();   // LASTNAME
wsDt.Column(4).AutoFit();   // AIRLINE
wsDt.Column(5).AutoFit();   // STATIONMODE
wsDt.Column(6).AutoFit();   // COUNTRYORIGIN
wsDt.Column(7).AutoFit();   // OBSERVATIONS
*/

// hide the gridlines of Worksheet
// wsDt.View.ShowGridLines = false; // true=show gridlines; false=hide gridlines.

// When Print the file, print letters and row numbers.
// wsDt.PrinterSettings.ShowHeaders = true;

// Print Title Row each pagebreak.
wsDt.PrinterSettings.RepeatRows = new ExcelAddress("1:1");

// set some document properties
package.Workbook.Properties.Title = "Enrollments Report";
package.Workbook.Properties.Author = "Kenny Mauricio";
package.Workbook.Properties.Comments = "Enrollments Report by Range";

// set some extended property values
package.Workbook.Properties.Company = "Kenny Mauricio";

// Set nee password over the file.
// package.Encryption.Algorithm = EncryptionAlgorithm.AES256;
// package.Encryption.Password = "Simple Pa$$word_1!!!";

// save the file.
package.Save();