NPOI复制范围到另一个工作表

时间:2012-05-17 08:31:26

标签: c# excel copy range npoi

我正在使用NPOI在C#中使用Excel。但是没有完整的文档如何使用它。我需要将一些范围复制到另一个工作表。有人知道怎么做这个吗?也许你正在使用另一个DLL(不是互操作)来提供这样的功能。如果是的话,请告诉我。

在excel中,一切都很简单:

Worksheets(2).rows(2).copy newsheet.Range("A1")

感谢您的回答!

1 个答案:

答案 0 :(得分:0)

NPOI不支持此功能,但是实现很简单。 这里有两个功能值得关注:CopyColumn()CopyRange()

CopyRangeExample()打开一个工作簿,创建一个新的输出工作表,并将单元格(数据和样式)从一个工作表复制到另一个工作表。

void CopyRangeExample()
{
  var workbook = OpenWorkbook("test.xlsx");

  var destinationSheetName = "destination" + (workbook.NumberOfSheets + 1).ToString();
  workbook.CreateSheet(destinationSheetName);

  ISheet sourceSheet = workbook.GetSheet("source");
  ISheet destinationSheet = workbook.GetSheet(destinationSheetName);

  CopyColumn("I", sourceSheet, destinationSheet);
  CopyRange(CellRangeAddress.ValueOf("C6:E15"), sourceSheet, destinationSheet);

  SaveWorkbook(workbook, "test.xlsx");
}

其余的代码:

void CopyRange(CellRangeAddress range, ISheet sourceSheet, ISheet destinationSheet)
{
  for (var rowNum = range.FirstRow; rowNum <= range.LastRow; rowNum++)
  {
    IRow sourceRow = sourceSheet.GetRow(rowNum);

    if (destinationSheet.GetRow(rowNum)==null)
      destinationSheet.CreateRow(rowNum);

    if (sourceRow != null)
    {
      IRow destinationRow = destinationSheet.GetRow(rowNum);

      for (var col = range.FirstColumn; col < sourceRow.LastCellNum && col<=range.LastColumn; col++)
      {
        destinationRow.CreateCell(col);
        CopyCell(sourceRow.GetCell(col), destinationRow.GetCell(col));
      }
    }
  }
}

void CopyColumn(string column, ISheet sourceSheet, ISheet destinationSheet)
{
  int columnNum = CellReference.ConvertColStringToIndex(column);
  var range = new CellRangeAddress(0, sourceSheet.LastRowNum, columnNum, columnNum);
  CopyRange(range, sourceSheet, destinationSheet);
}

void CopyCell(ICell source, ICell destination)
{
  if (destination != null && source != null)
  {
    //you can comment these out if you don't want to copy the style ...
    destination.CellComment = source.CellComment;
    destination.CellStyle = source.CellStyle;
    destination.Hyperlink = source.Hyperlink;

    switch (source.CellType)
    {
        case CellType.Formula:
            destination.CellFormula = source.CellFormula; break;
        case CellType.Numeric:
            destination.SetCellValue(source.NumericCellValue); break;
        case CellType.String:
            destination.SetCellValue(source.StringCellValue); break;
    }
  }
}

IWorkbook OpenWorkbook(string path)
{
  IWorkbook workbook;
  using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
  {
    workbook = WorkbookFactory.Create(fileStream);
  }
  return workbook;
}

void SaveWorkbook(IWorkbook workbook, string path)
{
  using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
  {
    workbook.Write(fileStream);
  }
}

仅记得在您的项目中包括NPOI和System.IO:

using NPOI.SS.UserModel;
using NPOI.SS.Util;
using System.IO;