我正在使用epplus在excel模板中在文件中写入大量信息,但之后我需要关闭ExcelPackage才能与Excel应用程序一起使用。它抛出了我的异常:“System.Runtime.InteropServices.COMException(0x800A03EC):来自HRESULT的异常:0x800A03EC”
private void FillCardsSheet()
{
xlPackage = new ExcelPackage(Template);
wsCards = xlPackage.Workbook.Worksheets[4];
string command = "SELECT * FROM dbo_serial_cards WHERE type <> 'EXT' AND LEFT([device_tag], 2) <> '!!'";
OleDbCommand cmd = new OleDbCommand(command, CON);
OleDbDataReader reader = cmd.ExecuteReader();
int row = 1;
while (reader.Read())
{
row++;
for (int col = 1; col <= 16; col++)
{
wsCards.Cells[row, col].Value = reader.GetValue(col - 1);
}
}
xlPackage.SaveAs(Template);
xlPackage.Dispose();
}
答案 0 :(得分:2)
很难说没有关于你的连接和对象的更多细节。什么是'模板'?如果你说哪一行产生错误可能会有帮助(如提到的@mason)。这是你似乎得到的COM错误,所以它可能与数据库连接或包本身有关。由于在方法之外管理包,因此确保它没有被锁定或关闭。
这对我连接本地SQL Server数据库很好:
[TestMethod]
public void SQL_Reader_Test()
{
var Template = new FileInfo(@"c:\temp\temp.xlsx");
if (Template.Exists)
Template.Delete();
var xlPackage = new ExcelPackage(Template);
//var wsCards = xlPackage.Workbook.Worksheets[4];
var wsCards = xlPackage.Workbook.Worksheets.Add("Cards");
//const string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\temp\northwind.mdb;Persist Security Info=False;";
const string constring = @"Provider=SQLNCLI11;Data Source=MYMACHINENAME\SQLEXPRESS;Initial Catalog=AdventureWorks;UID=AdventureWorks; Pwd=AdventureWorks";
using (var CON = new OleDbConnection(constring))
{
CON.Open();
//string command = "SELECT * FROM dbo_serial_cards WHERE type <> 'EXT' AND LEFT([device_tag], 2) <> '!!'";
const string command = "SELECT * FROM Person.Address";
var cmd = new OleDbCommand(command, CON);
var reader = cmd.ExecuteReader();
int row = 1;
while (reader.Read())
{
row++;
//for (int col = 1; col <= 16; col++)
for (int col = 1; col <= reader.FieldCount; col++)
{
wsCards.Cells[row, col].Value = reader.GetValue(col - 1);
}
}
xlPackage.SaveAs(Template);
xlPackage.Dispose();
}
}
答案 1 :(得分:0)
尝试在Using-Block中使用ExcelPackage:
using (ExcelPackage xlsPackage = new ExcelPackage(Template))
{
// Your Code
xlPackage.SaveAs(Template);
}