我正在尝试打开(或创建新的 xls)Excel 文件并向其中写入一些值。虽然,如果我只是创建一个新的 xls 文件,下面的程序就可以正常工作,但我遇到了一些问题
**mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);**
这是错误:无法访问“LOG.xls”。该文件可能已损坏、位于没有响应的服务器上或只读。它不是只读的,也没有损坏(因为有时文件是在运行时创建的)。那有什么问题呢?
private static Microsoft.Office.Interop.Excel.Workbook mWorkBook;
private static Microsoft.Office.Interop.Excel.Sheets mWorkSheets;
private static Microsoft.Office.Interop.Excel.Worksheet mWSheet1;
private static Microsoft.Office.Interop.Excel.Application oXL;
private void btnSignIn_Click ( object sender, EventArgs e )
{
string path = "D:\\LOG.xls";
if(!File.Exists(path))
{
File.Create (path);
}
oXL = new Microsoft.Office.Interop.Excel.Application ();
oXL.Visible = true;
oXL.DisplayAlerts = false;
//error on this line
mWorkBook = oXL.Workbooks.Open (path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);
//Get all the sheets in the workbook
mWorkSheets = mWorkBook.Worksheets;
//Get the allready exists sheet
mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item ("Sheet1");
Microsoft.Office.Interop.Excel.Range range = mWSheet1.UsedRange;
int colCount = range.Columns.Count;
int rowCount = range.Rows.Count;
for ( int index = 1; index < 15; index++ )
{
mWSheet1.Cells [rowCount + index, 1] = rowCount + index;
mWSheet1.Cells [rowCount + index, 2] = "New Item" + index;
}
mWorkBook.SaveAs (path, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive,
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value);
mWorkBook.Close (Missing.Value, Missing.Value, Missing.Value);
mWSheet1 = null;
mWorkBook = null;
oXL.Quit ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
GC.WaitForPendingFinalizers ();
GC.Collect ();
}