Error on Saving Excel file using worksheet.save()
The error is:
Exception from HRESULT:开发者_运维问答 0x800A03EC.
I've experience this once. I was opening the Excel file while I am writing my Excel sheet. So, I've solved it by posponding the file opening until finishing the saving operation.
This is just a guess, but it has caused me grief in the past...
There's a bug in excel (and perhaps other office products) that gives this errorcode when calling methods using another culture than English.
The correct way of dealing with this is to change the culture:
CultureInfo oldCulture = Thread.CurrentThread.CurrentCulture;
try {
// use excel here
} finally { // restore culture
Thread.CurrentThread.CurrentCulture = oldCulture;
}
I've written a class to help with this. You can use it as this:
using(new RunInCulture.English) {
// use excel here
}
And here's the code:
public class RunInCulture : IDisposable
{
CultureInfo _oldCulture;
public RunInCulture(string culture)
: this(CultureInfo.GetCultureInfo(culture))
{
}
public RunInCulture(CultureInfo culture)
{
_oldCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = culture;
}
public static RunInCulture Invariant
{
get
{
return new RunInCulture(CultureInfo.InvariantCulture);
}
}
public static RunInCulture English
{
get
{
return new RunInCulture("en-US");
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing)
Thread.CurrentThread.CurrentCulture = _oldCulture;
}
~RunInCulture()
{
Dispose(false);
}
}
public class EnglishCulture : RunInCulture
{
public EnglishCulture()
: base("en-US")
{
}
}
I solved this issue changing the way I reference the workbook that needs to be saved.
Way 1
var wkb = excelInstance.Workbooks[1];
wkb.SaveAs(targetReportPath);
// This works
Way 2
excelInstance.ThisWorkbook.SaveAs(targetReportPath);
// This fails...
精彩评论