有一个用于 Excel 的 ADO.NET 提供程序。
这意味着,如果您有一个数据集,您可以使用两个 DataAdapter 将数据从一个地方移动到另一个地方:从 Oracle 到 Excel,从 SQL 到 Excel,从 Excel 到 Oracle,等等。
使用第一个 DA 从源填充 DataSet,然后使用第二个 DA 更新目标。 DataAdapter 不需要是同一类型 - 您可以使用任何 OleDbDataAdapter、SqlDataAdapter、OracleDataAdapter 等进行读取和更新。
无需摆弄 CSV 或 XML 格式。无需使用办公自动化,因此无需 PIA,它可以在服务器上运行。它只是 ADO.NET。
要连接到 Excel,请使用 Microsoft.Jet.OLEDB oledb 提供程序。
Full Example source。
摘录:
System.Data.DataSet ds1;
const string ConnStringSql= "Provider=sqloledb;Data Source=dinoch-8;Initial Catalog=Northwind;Integrated Security=SSPI;" ;
const string OutputFilename= "ExtractToExcel.xls";
const string ConnStringExcel=
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + OutputFilename + ";" +
"Extended Properties=\"Excel 8.0;HDR=yes;\""; // FIRSTROWHASNAMES=1;READONLY=false\"
const string sqlSelect="SELECT top 10 ProductId, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock, GETDATE() as Extracted from Products order by UnitPrice";
const string sqlInsert="INSERT INTO Extracto (ProductId, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock, Extracted) VALUES (@ProductId, @ProductName, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @Extracted)";
private void ReadFromSql()
{
var ConnSql= new System.Data.OleDb.OleDbConnection(ConnStringSql);
var da1 = new System.Data.OleDb.OleDbDataAdapter();
da1.SelectCommand= new System.Data.OleDb.OleDbCommand(sqlSelect);
da1.SelectCommand.Connection= ConnSql;
ds1= new System.Data.DataSet();
da1.Fill(ds1, "Extracto");
}
private void InsertIntoExcel()
{
// need to update the row so the DA does the insert...
foreach (System.Data.DataRow r in ds1.Tables[0].Rows)
{
r.SetModified(); // mark the row as updated to force an insert
}
var da2 = new System.Data.OleDb.OleDbDataAdapter();
da2.UpdateCommand= new System.Data.OleDb.OleDbCommand(sqlInsert);
da2.UpdateCommand.Connection= ConnExcel;
da2.UpdateCommand.Parameters.Add("@ProductId", System.Data.OleDb.OleDbType.Integer, 4, "ProductId");
da2.UpdateCommand.Parameters.Add("@ProductName", System.Data.OleDb.OleDbType.VarWChar, 40, "ProductName");
da2.UpdateCommand.Parameters.Add("@QuantityPerUnit", System.Data.OleDb.OleDbType.VarWChar, 20, "QuantityPerUnit");
da2.UpdateCommand.Parameters.Add("@UnitPrice", System.Data.OleDb.OleDbType.Currency, 8, "UnitPrice");
da2.UpdateCommand.Parameters.Add("@UnitsInStock", System.Data.OleDb.OleDbType.SmallInt, 2, "UnitsInStock");
da2.UpdateCommand.Parameters.Add("@Extracted", System.Data.OleDb.OleDbType.Date, 8, "Extracted");
da2.Update(ds1, "Extracto");
}
这不是 Excel 自动化,因此适用于在服务器上使用 Excel 自动化的注意事项不适用。
您可以从现有的 XLS 文件(或 XLSX)开始,然后填写一个命名范围。这使您有机会在插入 ilve 数据之前应用格式等。本质上,现有的 XLS 文件是一个模板。
或者,您可以从零开始,在运行时完全动态地创建 XLS 文件和 XLS 文件中的表/范围。在这种情况下,XLS 文件将非常普通/普通。没有格式、颜色、公式等。