我正在尝试将多张工作表中的数据附加到同一工作簿中,并将它们附加到第一张工作表中。
这是我能够完成的事情:
void SomeMethod()
{
HSSFWorkbook hssfwb;
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfwb = new HSSFWorkbook(file);
}
var BaseSheet = workbook.GetSheetAt(0);
for (int i = 1; i < workbook.NumberOfSheets; i++)
{
AddRowsToBaseSheet(BaseSheet, workbook.GetSheetAt(i), workbook);
}
}
private void AddRowsToBaseSheet(ISheet BaseSheet, ISheet sheet, HSSFWorkbook workbook)
{
var temp = sheet.GetRowEnumerator();
while (temp.MoveNext())
{
HSSFRow sourceRow = (HSSFRow)temp.Current;
HSSFRow destinationRow = (HSSFRow)BaseSheet.CreateRow(BaseSheet.LastRowNum + 1);
CopyRow(workbook, sourceRow, destinationRow);
}
}
private void CopyRow(HSSFWorkbook workbook, IRow sourceRow, IRow destinationRow)
{
// Loop through source columns to add to new row
for (int i = 0; i < sourceRow.LastCellNum; i++)
{
// Grab a copy of the old/new cell
ICell oldCell = sourceRow.GetCell(i);
ICell newCell = destinationRow.CreateCell(i);
// If the old cell is null jump to next cell
if (oldCell == null)
{
newCell = null;
continue;
}
// Set the cell data type
newCell.SetCellType(oldCell.CellType);
// Set the cell data value
switch (oldCell.CellType)
{
case CellType.Blank:
newCell.SetCellValue(oldCell.StringCellValue);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellErrorValue(oldCell.ErrorCellValue);
break;
case CellType.Formula:
newCell.SetCellFormula(oldCell.CellFormula);
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.String:
newCell.SetCellValue(oldCell.RichStringCellValue);
break;
case CellType.Unknown:
newCell.SetCellValue(oldCell.StringCellValue);
break;
}
}
}
我可能会犯一个愚蠢的错误,或者是否还有其他库?
在这种情况下,转换为数据集不起作用,因为列不相关