我正在编写一个程序,使用 oledb 将数据发送到 excel。我使用了如下更新语句:
OleDbConnection MyConnection = new OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + GeneralData.excelPath + "';Extended Properties=Excel 8.0;")
MyConnection.Open();
OleDbCommand myCommand = new OleDbCommand();
myCommand.Connection = MyConnection;
myCommand.CommandType = System.Data.CommandType.Text;
string sql = "Update [test$] set press = " + pointsProperties[i].Pressure + ", temp = " + pointsProperties[i].Temperature + " where id= " + id;
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
问题是我会使用 sql 语句超过 100 次,这需要很多时间,所以我认为使用数据表会花费更少的时间,所以我写了一个代码将我的数据保存在数据表中,如下所示:
public static System.Data.DataTable ExcelDataTable = new System.Data.DataTable("Steam Properties");
static System.Data.DataColumn columnID = new System.Data.DataColumn("ID", System.Type.GetType("System.Int32"));
static System.Data.DataColumn columnPress = new System.Data.DataColumn("Press", System.Type.GetType("System.Int32"));
static System.Data.DataColumn columnTemp = new System.Data.DataColumn("Temp", System.Type.GetType("System.Int32"));
public static void IntializeDataTable() // Called one time in MDIParent1.Load()
{
columnID.DefaultValue = 0;
columnPress.DefaultValue = 0;
columnTemp.DefaultValue = 0;
ExcelDataTable.Columns.Add(columnID);
ExcelDataTable.Columns.Add(columnPress);
ExcelDataTable.Columns.Add(columnTemp);
}
public static void setPointInDataTable(StreamProperties Point)
{
System.Data.DataRow ExcelDataRow = ExcelDataTable.NewRow(); // Must be decleared inside the function
// It will raise exception if decleared outside the function
ExcelDataRow["ID"] = Point.ID;
ExcelDataRow["Press"] = Point.Pressure;
ExcelDataRow["Temp"] = Point.Temperature;
ExcelDataTable.Rows.Add(ExcelDataRow);
}
问题是我不知道:
1-第二种方式更快吗?
2-如何将数据表复制到excel文件中?
谢谢。