我尝试读取现有的excel文件并复制到另一个路径,然后我尝试将数据插入到克隆的文件中。但我可以'插入数据。我不知道我犯了什么错误。但在这里我给了我的代码。
行sheetData.InsertAt<Row>(row,++rowIndex);
出错。请帮帮我。
Package spreadsheetPackage = Package.Open(destinationFile, FileMode.Open, FileAccess.ReadWrite);
using (var document = SpreadsheetDocument.Open(spreadsheetPackage))
{
foreach (System.Data.DataTable table in ds.Tables)
{
var workbookPart = document.WorkbookPart;
var workbook = workbookPart.Workbook;
var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault();
Worksheet ws = ((WorksheetPart)(workbookPart.GetPartById(sheet.Id))).Worksheet;
SheetData sheetData = ws.GetFirstChild<SheetData>();
//Sheet sheet = sheets.FirstOrDefault();
if(sheet==null)
throw new Exception("No sheed found in the template file. Please add the sheet");
int rowIndex = 10, colIndex = 0;
bool flag = false;
var worksheetPart = (WorksheetPart)workbookPart.GetPartById(sheet.Id);
var sharedStringPart = workbookPart.SharedStringTablePart;
var values = sharedStringPart.SharedStringTable.Elements<SharedStringItem>().ToArray();
var rows = worksheetPart.Worksheet.Descendants<Row>();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in table.Columns)
{
columns.Add(column.ColumnName);
}
foreach (System.Data.DataRow dsrow in table.Rows)
{
Row row = new Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString());
row.AppendChild<Cell>(cell);
}
sheetData.InsertAt<Row>(row,++rowIndex);
}
}
答案 0 :(得分:2)
在添加Row之前,您应该提到实例的行索引...
row.RowIndex = (UInt32)rowIndex++;