简单的使用NPOI读取和生成Excel文件

 
   
 
   
 
   
 
   
//打开Excel文件
using (FileStream excelfs = new FileStream("c:\\workbook.xls", FileMode.Open, FileAccess.Read))
{
    //根据“文件流”来创建HSSFWorkbook,即整个excel的工作簿
    HSSFWorkbook workbook = new HSSFWorkbook(excelfs);
    //获取excel的第一个sheet工作表
    HSSFSheet sheet = (HSSFSheet)workbook.GetSheetAt(0);
    //循环读取所有行的内容
    for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
    {
        DataRow newRow = table.NewRow();
        //读取excel的行
         HSSFRow row = (HSSFRow)sheet.GetRow(i);
        if (row != null)
        {
            if (row.GetCell(0) != null)
            {
                //复制整行数据
                  for (int j = row.FirstCellNum; j < row.Cells.Count; j++)
                {
                    newRow[j] = row.GetCell(j);
                }
                //添加到数据表中
                  table.Rows.Add(newRow);
            }
        }
    }
}

生成Excel文件:

//新建workbook工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//新建sheet工作表
HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet();      
//设置默认列宽
sheet.DefaultColumnWidth = 15;
//填充工作表的内容
for (int i = 0; i < dataSource.Count; i++)
{
    //新建row数据行
    HSSFRow dataRow = (HSSFRow)sheet.CreateRow(i);
    //填充数据行的内容
    for (int j = 0; j < dataSource.ToArray().Count(); j++)
    {
        //新建cell单元格并填充内容
        dataRow.CreateCell(j).SetCellValue(dataSource[i][j].ToString());
    }
}
//保存文件
using (FileStream fs = new FileStream("c:\\workbook.xls", FileMode.Create, FileAccess.Write))
{
    workbook.Write(fs);
}

你可能感兴趣的:(简单的使用NPOI读取和生成Excel文件)