[英]Cannot save Excel file after updating it in c# console app
信息:
已安裝 MS Excel 版本:Excel 2013(如果需要,可以嘗試更改)
使用的參考庫:Microsoft Excel 15.0 對象庫(1.8 版)
.Net 框架:4.7.2(無法更改)
應用程序類型:控制台應用程序(無法更改)
我需要的:
所以我有一個 excel 工作簿,它在前 2 個工作表中已經有大約 8000 行,在其他 4 個工作表中已經有一些圖表。 我需要將此數據添加到前兩張工作表之一中現有數據的底部,進行刷新,保存並關閉它。
這就是我在做什么:
using MSExcel = Microsoft.Office.Interop.Excel;
在類構造函數中——
public UsageReportFileManager(string reportFolderPath)
{
excel = new MSExcel.Application();
if (excel == null)
{
log.Error("-E-Unable to create report!!");
throw new Exception("Microsoft excel is not installed on the client machine");
}
InitializeWorkbook();
}
初始化工作簿功能---
private void InitializeWorkbook()
{
if (excel != null)
{
var filePath = GetResultPath(); //This returns a path which ends with .xlsx and it is a path to the existing file.
if (!File.Exists(filePath)) //This is just handling a situation in case the actual file is missing.
{
//Create copy from template
var templatePath = GetTemplateFilePath(); // this is not a excel template btw, its a empty workbook with formulas.
File.Copy(templatePath, filePath);
// Till here its working and new file is created if original file is missing
}
var missing = Missing.Value;
_workbook = excel.Workbooks.Open(Filename: filePath,
UpdateLinks: missing,
ReadOnly: false,
Format: missing,
Password: missing,
WriteResPassword: missing,
IgnoreReadOnlyRecommended: true,
Origin: missing,
Delimiter: missing,
Editable: true,
Notify: missing,
Converter: missing,
AddToMru: true,
Local: true
);
}
}
在這個類中的一個單獨的函數中,它在這個類被初始化后從 Program.cs 調用——
public void UpdateLoginRawDataToWorkbook(List<HubAuditEvent> lstLoginData)
{
var dtLoginData = ConvertDataListToDatatable(lstLoginData); -- I will be getting more than 1500 rows here.
if (dtLoginData.Rows.Count > 0)
{
MSExcel.Worksheet sheet = _workbook.Sheets["SheetAlreadyHasData"] as MSExcel.Worksheet;
MSExcel.Range lastCell = sheet.Cells.Find(
"*",
Missing.Value,
Missing.Value,
Missing.Value,
MSExcel.XlSearchOrder.xlByRows,
MSExcel.XlSearchDirection.xlPrevious,
false,
Missing.Value,
Missing.Value);
int lastRow = lastCell.Row;
for (int i = 0; i < dtLoginData.Rows.Count; i++)
{
int row = lastRow + i + 1;
for (int j = 0; j < dtLoginData.Columns.Count; j++)
{
var col = j + 1;
sheet.Cells[row, col] = dtLoginData.Rows[i][j].ToString();
}
}
_workbook.RefreshAll();
excel.Calculate();
_workbook.Save(); <-- I get an exception here saying Cannot Save Read-Only file ..
_workbook.Close(true);
excel.Quit();
}
我在_workbook.Save();
處得到一個異常_workbook.Save();
行說無法保存只讀文件..
好的,所以我將其發布為答案而不是評論,因為我相信我們中的許多人可能會在沒有意識到的情況下做同樣的事情。
特別感謝@PanagiotisKanavos 和@MikeJ:你們拯救了我的一天。 你的評論讓我覺得我真的打開了“再次”文件?
我說“再次”因為這就是發生的事情......
所以我打開文件,檢查它是否只讀並運行我的控制台應用程序。 (見這里我忘記關閉桌面應用程序上的工作簿)
然后在調試過程中,我收到了打開的異常,所以我在看到異常的那一刻就停止調試。 (這是第一件事,因為我只是在測試,我忘記將 excel.Quit() 放在 finally 塊中——我現在意識到這是非常非常重要的。即使我在 finally 塊中擁有它,第二個錯誤我正在做的是我在遇到異常的那一刻就停止了應用程序)。
現在我有幾個未關閉的打開 excel 對象實例,因為到目前為止我已經調試了幾次。 從那時起,無論我將 excel.Quit() 放在哪里,該實例都會出於某種原因在某處打開。
然后我檢查了您的評論並嘗試再次手動打開並收到與其只讀相同的錯誤消息。 那時一切都非常清楚。
現在我在 FileManager 類中創建了一個名為 Close() 的公共方法,它看起來像:
public void Close() { if(excel != null && _workbook != null) { _workbook.Close(true); excel.Quit(); } }
現在我從 Program.cs 類的 finally 塊中調用了這個 Close() 方法。
現在它工作正常。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.