NPOI converting XLS to XLSX throwing null reference

时间:2015-09-01 23:01:58

标签: c# excel npoi

I'm trying to convert a file from XLS to XLSX using NPOI. As I'm not aware of an explicit conversion, I wrote this first implementation going through the rows and cells and copying from one to another:

public string ConvertToXlsx(string xlsPath)
    {
        var oldWorkbook = new HSSFWorkbook(new FileStream(xlsPath, FileMode.Open));
        var oldWorkSheet = oldWorkbook.GetSheetAt(0);
        var newExcelPath = xlsPath.Replace("xls", "xlsx");
        using (var fileStream = new FileStream(newExcelPath, FileMode.Create))
        {
            var newWorkBook = new XSSFWorkbook();
            var newWorkSheet = new XSSFSheet();
            newWorkBook.Add(newWorkSheet);

            foreach (HSSFRow oldRow in oldWorkSheet)
            {
                var newRow = newWorkSheet.CreateRow(oldRow.RowNum);

                for (int ii = oldRow.FirstCellNum; ii < oldRow.LastCellNum; ii++)
                {
                    var newCell = newRow.CreateCell(ii);
                    newCell = oldRow.Cells[ii];
                }
            }

            newWorkBook.Write(fileStream);
        }

        return newExcelPath;
    }

Yet, on line var newCell = newRow.CreateCell(ii); NPOI throws a NullReferenceException With the following stack trace:

at NPOI.XSSF.UserModel.XSSFCell..ctor(XSSFRow row, CT_Cell cell)
at NPOI.XSSF.UserModel.XSSFRow.CreateCell(Int32 columnIndex, CellType type)
at NPOI.XSSF.UserModel.XSSFRow.CreateCell(Int32 columnIndex)
at Ing2Ynab.Excel.IngExcelConverter.ConvertToXlsx(String xlsPath)

Which I don't get why it's happening, as XSSFRow should be in charge of creating the CT_Cell that gets passed on to XSSFCell constructor, from what I could read in NPOIs code.

Has anyone else tried to do this and/or has fixed it?

Thanks.

1 个答案:

答案 0 :(得分:1)

看起来你必须显式调用Workbooks CreateSheet()方法而不是调用.Add()。此外,您似乎在循环中有一些超出范围的异常,因此请留意这一点。

public string ConvertToXlsx(string xlsPath)
    {
        var oldWorkbook = new HSSFWorkbook(new FileStream(xlsPath, FileMode.Open));
        var oldWorkSheet = oldWorkbook.GetSheetAt(0);
        var newExcelPath = xlsPath.Replace("xls", "xlsx");
        using (var fileStream = new FileStream(newExcelPath, FileMode.Create))
        {
            var newWorkBook = new XSSFWorkbook();
            var newWorkSheet = newWorkBook.CreateSheet("Sheet1");

            foreach (HSSFRow oldRow in oldWorkSheet)
            {
                var newRow = newWorkSheet.CreateRow(oldRow.RowNum);

                for (int ii = oldRow.FirstCellNum; ii < oldRow.LastCellNum; ii++)
                {
                    var newCell = newRow.CreateCell(ii);
                    newCell = oldRow.Cells[ii];
                }
            }

            newWorkBook.Write(fileStream);
        }

        return newExcelPath;
    }