用OLEDB

问题描述 投票:0回答:1

这是我试图写信给Excel

的方式

private void GenerateReport() { FileInfo xlsFileInfo = new FileInfo(Server.MapPath(CE_REPORTS_PATH + CE_PTIN_TEMPLATE + EXTENSION)); string connectionString = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes'", xlsFileInfo.FullName); //create connection OleDbConnection oleDBConnection = new OleDbConnection(connectionString); oleDBConnection.Open(); //create the adapter with the select to get OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$A16:F16]", oleDBConnection); // Create the dataset and fill it by using the adapter. DataTable dataTable = new DataTable(); adapter.FillSchema(dataTable, SchemaType.Source); adapter.Fill(dataTable); string[] colNames = new string[dataTable.Columns.Count]; string[] colParms = new string[dataTable.Columns.Count]; for (int i = 0; i < dataTable.Columns.Count; i++) { colNames[i] = String.Format("[{0}]", dataTable.Columns[i].ColumnName); colParms[i] = "?"; } // Create Insert Command adapter.InsertCommand = new OleDbCommand(String.Format("INSERT INTO [Sheet1$] ({0}) values ({1})", string.Join(",", colNames), string.Join(",", colParms)), oleDBConnection); // Create Paramaters for (int i = 0; i < dataTable.Columns.Count; i++) { OleDbParameter param = new OleDbParameter(String.Format("@[{0}]", dataTable.Columns[i].ColumnName), OleDbType.Char, 255, dataTable.Columns[i].ColumnName); adapter.InsertCommand.Parameters.Add(param); } // create a new row DataRow newCERecord = dataTable.NewRow(); // populate row with test data for (int i = 0; i < dataTable.Columns.Count; i++) { newCERecord[i] = "new Data"; } dataTable.Rows.Add(newCERecord); // Call update on the adapter to save all the changes to the dataset adapter.Update(dataTable); oleDBConnection.Close(); }

当调用Adapter.update(DataTable)时,我会发生错误

$ exception {“插入语句中包含以下未知字段名称:'参与者名字'。确保您已正确键入该名称,然后再次尝试操作。 }

这令人沮丧,因为我直接从Colnames [i] = string.format(“ [{0}]”获得的每个字段从列名中拉出每个字段,datatable.columns [i] .columnname)。我发现我需要[]来说明列名中的空间,但是此时我不确定问题所在。当我查看excel文件时,一切对我来说似乎都是正确的。
    

我实际上为您找到了一篇Microsoft文章,其中已完成整个代码 - 您可能可以复制和粘贴最喜欢的解决方案。这是链接:

http://support.microsoft.com/kb/306023

c# oledb export-to-excel oledbdataadapter
1个回答
4
投票

eDit

:为了完整,这是我的原始答案。请参阅上面的链接,以获取更多详细信息,并提供更好的解决方案。

这不是您问题的答案,而是改变您的方法的建议(如果可以的话)。通过COM调用添加数据时,Excel往往非常慢,我认为OLEDB内部使用COM。以我的经验,最快的(巧合的是最痛苦的方法)输出数据是出于excel的输出数据,它将生成一个带有所有数据的选项卡分隔文本文件,然后将文件导入到Excel中,然后使用COM Interop在表上执行任何格式。当我以这种方式生成Excel报告时,与使用Excel COM对象模型相比,我的大多数报告过去几乎生成了几乎100倍。 (I don't know if this would be the same for OleDB calls, since I've never used OleDB with Excel but I'd be willing to bet the OleDB adapter uses COM internally.) 这也会照顾您的嵌入式空间问题,因为选项卡将是列分隔符。

In your particular situation, I'd import the text file into Excel into a new sheet and then copy & paste it into the IRS sheet, at the right location.完成后,可以删除临时表。


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.