2013-05-13 32 views
0

。我正在使用下面的方法來插入公式。其插入式正確配方工作正常。 但是當我公式插入我的excel文件得到corrpted並顯示插入公式給出錯誤。Excel在「ab.xlsx」中發現不可讀的內容。你是否想要恢復我要求插入單元格公式的

「的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(); 
    } 
} 
+0

* exceltemplate。** aspx ***聽起來不太合適... – 2013-05-13 11:31:01

+0

sry ..它的.xlsx @DanielHilgarth – 2013-05-13 12:22:42

回答

1

這個函數有兩個問題。

第一個問題是您明確將RowIndex設置爲4U。您將公式分配給的單元格必須位於第4行,比如單元格C4。由於單元格引用是作爲參數傳遞的(strCellIndex),所以不能保證。

即使你固定的,我們有一個(也是更陰險)的問題...

第二個問題是有點難以修復。 Row類必須按照RowIndex的順序插入到SheetData類中(作爲子對象)。假設您仍然希望將RowIndex硬編碼爲4U。這意味着如果現有的Excel文件具有第2,3和7行,則必須使用RowIndex 3將Row類插入Row類後面。這非常重要,否則Excel將抽血(正如您已經體驗過的那樣)。

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

我會給你留下一個有趣的錯誤檢查任務,比如如果沒有Row類開始,或者所有Row類的RowIndex-es小於你要插入的Row類,或者(這裏是有趣的一個)與您要插入的Row類具有相同RowIndex的現有Row類。

+0

我刪除了rowindex 4U,現在動態傳遞rowindex。它的工作美麗。非常感謝。 – 2013-05-14 07:07:02