2

我有一个 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 语句中的语法错误。

4

2 回答 2

0

试试这个语法:

myCommand.CommandText = "Insert into [Sheet1$] (id,name) values('5','e')";
于 2012-09-13T06:44:32.487 回答
-1

我希望你一切都好。您可以使用 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();
于 2020-10-03T12:58:44.363 回答