NPOI SetCellValue方法不会将数据写入单元格 [英] NPOI SetCellValue method doesn't write data to cells

查看:2028
本文介绍了NPOI SetCellValue方法不会将数据写入单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用NPOI将数据写入Excel工作表单元时遇到一些问题. 这是我的代码:

I have some problem with writing data to Excel worksheet cells using NPOI. Here is my code:

        FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read);
        hssfworkbook = new HSSFWorkbook(file);
        ISheet sheet1 = hssfworkbook.GetSheet("Табель");
        for (int i = 0; i < table.Tables[0].Rows.Count; i++)
        {
            for (int j = 0; j < table.Tables[0].Columns.Count; j++)
            {
                if (table.Tables[0].Rows[i][j].ToString() != "0")
                    sheet1.GetRow(i+5).GetCell(j).SetCellValue(table.Tables[0].Rows[i][j].ToString());
                else
                    sheet1.GetRow(i+5).GetCell(j).SetCellValue("");
            }
        }
        string save_path = Server.MapPath("~/templates/report_new.xls");
        FileStream save_file = new FileStream(save_path, FileMode.Create);
        hssfworkbook.Write(save_file);
        save_file.Close();

我知道打开现有工作表的过程是可行的,因为在运行此代码后,我有一个名为"report_new"的新保存的工作表.它会正确打开一个现有的工作表,因为新保存的文件内部具有相同的模板.但是它没有我需要的数据.因此,循环中的SetCellValue方法不起作用,也不会将数据写入单元格.我检查了由名为表"的数据集表示的数据源是否为空,因此数据存在.但是它不会将其写入单元格. 这可能是什么问题?

I know that the process of opening existing worksheet works, because I have a new saved worksheet named "report_new" after this code runs. It correctly opens an existing worksheet because the newly saved file has the same template inside. But it has no data I needed. So SetCellValue method in the loop doesn't work and doesn't write data to cells. I checked that my data source represented by the DataSet named "table" isn't empty, so data exists. But it doesn't write it to cells. What can be the problem here?

推荐答案

尝试以下方法之一将其写入excel单元格

Try one of these approaches to write into the cell of excel

   var row = sheet.CreateRow(0);
   row.CreateCell(j).SetCellValue(table.Tables[0].Rows[i][j].ToString());

    // or 
    row.Cells[j].SetCellValue(table.Tables[0].Rows[i][j].ToString());


    // Or 


    ISheet sheet1 = hssfworkbook.GetSheet("Табель");
    for (int i = 0; i < table.Tables[0].Rows.Count; i++)
    {  
            HSSFRow row = (HSSFRow)sheet1.GetRow(i+5);

        for (int j = 0; j < table.Tables[0].Columns.Count; j++)
        {
    if (table.Tables[0].Rows[i][j].ToString() != "0")
        row.GetCell(j).SetCellValue(table.Tables[0].Rows[i][j].ToString());
    else
        row.GetCell(j).SetCellValue("");
        }
    }

这篇关于NPOI SetCellValue方法不会将数据写入单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆