我的要求是为单元格插入公式。我正在使用以下方法插入公式。并且其插入配方和配方工作正常。 但是当我插入公式时,我的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();
}
}
答案 0 :(得分:1)
该功能有2个问题。
第一个问题是您明确将RowIndex设置为4U。您分配公式的单元格必须位于第4行,比如单元格C4。由于单元格引用作为参数(strCellIndex)传入,因此无法保证。
即使你解决了这个问题,我们也会遇到下一个(而且更加阴险)的问题......
第二个问题有点难以解决。 Row类必须在SheetData类(作为子对象)中按顺序插入,由RowIndex排序。假设您仍然希望将RowIndex硬编码为4U。这意味着如果现有的Excel文件包含第2,3和7行,则必须使用RowIndex 3在Row类后面插入Row类。这很重要,否则Excel会呕血(正如您已经体验过的那样)。
第二个问题的解决方案需要更多的工作。考虑SheetData类的函数InsertAt(),InsertBefore()和InsertAfter()(实际上是大多数Open XML SDK类)。迭代SheetData的子类,直到找到RowIndex大于您要插入的Row类的Row类。然后使用InsertBefore()。
我将为您提供错误检查的有趣任务,例如,如果没有要开始的Row类,或者所有Row类的RowIndex-es小于您要插入的Row类,或者(这是有趣的一个)现有的Row类与您要插入的Row类具有相同的RowIndex。