簡體   English   中英

插入給出錯誤的公式。Excel在“ ab.xlsx”中發現了不可讀的內容。 您是否要恢復

[英]Inserting formula giving error.. Excel found unreadable content in “ab.xlsx”. Do you want to recover the

我的要求是為單元格插入公式。 我正在使用以下方法來插入公式。 並且其核心插入公式和公式工作良好。 但是當我插入公式時,我的excel文件已被更正並顯示消息

“ Excel在“ exceltemplate.xlsx”中發現了不可讀的內容

您是否要恢復...的內容?”。我搜索了很多,但沒有解決。請幫助解決此問題

public void InsertFormula(string filepath, string SheetName, string strCellIndex, string strFormula)
{
    using (SpreadsheetDocument document = SpreadsheetDocument.Open(filepath, true))
    {
        IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().Where(s => s.Name == SheetName);
        if (sheets.Count() == 0)
        {
            // The specified worksheet does not exist.
            return;
        }
        WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
        Worksheet worksheet = worksheetPart.Worksheet;
        SheetData sheetData = worksheet.GetFirstChild<SheetData>();

        Row row1 = new Row()
        {
            RowIndex = (UInt32Value)4U,
            Spans = new ListValue<StringValue>()
        };

        Cell cell = new Cell() { CellReference = strCellIndex };
        CellFormula cellformula = new CellFormula();
        cellformula.Text = strFormula;
        cell.DataType = CellValues.Number;
        CellValue cellValue = new CellValue();
        cellValue.Text = "0";
        cell.Append(cellformula);
        cell.Append(cellValue);
        row1.Append(cell);

        sheetData.Append(row1);
        worksheet.Save();
        document.Close();
    }
}

該功能有兩個問題。

第一個問題是您將RowIndex顯式設置為4U。 您要為其分配公式的單元格必須位於第4行,即單元格C4。 由於單元格引用作為參數(strCellIndex)傳入,因此不能保證。

即使您解決了此問題,我們也會遇到下一個(更陰險的)問題...

第二個問題很難解決。 必須按RowIndex的順序在SheetData類(作為子對象)中按順序插入Row類。 假設您仍然希望將RowIndex硬編碼為4U。 這意味着如果現有的Excel文件具有第2、3和7行,則必須在Row類后面插入帶有RowIndex 3的Row類。這很重要,否則Excel會吐血(如您所知)。

解決第二個問題需要更多的工作。 考慮SheetData類(或實際上大多數Open XML SDK類)的InsertAt(),InsertBefore()和InsertAfter()函數。 遍歷SheetData的子類,直到找到RowIndex大於要插入的Row類的Row類。 然后使用InsertBefore()。

我將為您提供有趣的錯誤檢查任務,例如,如果沒有Row類開始,或者所有Row類的RowIndex-小於要插入的Row類,或者(這里很有趣)與要插入的Row類具有相同RowIndex的現有Row類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM