如何使用NPOI读取上载的Excel文件,而不是存储在服务器或项目中

时间:2013-12-23 10:05:12

标签: c# npoi

我的示例代码在下面使用NPOI.dll。我可以阅读EXCEL文件(即Excel将存储在系统中,如D:/Jamal/Test.xls。然后dll很容易阅读内容,但我需要阅读上传的Excel文件而不将其存储在任何地方.HTTPPOSTEDFILEBASE excelfile具有Excel文件的价值,但我需要知道如何使用NPOI dll读取它

public List<string> SendInvitesExcelFile1(List<String> CorrectMailIDs,
                                     ListInvites Invites, HttpPostedFileBase excelfile)
{
        List<string> mailids = new List<string>();
        //string filename = (excelfile.FileName).ToString();
        HSSFWorkbook hssfwb;
    //   using (FileStream file = new FileStream(@"D:\test.xls", FileMode.Open, FileAccess.Read))

         using (FileStream file = new FileStream(excelFile.FileName, FileMode.Open, FileAccess.Read))
        { 
             hssfwb = new HSSFWorkbook(file);
        }

        Sheet sheet = hssfwb.GetSheet("sheet1");
        for (int row = 0; row <= sheet.LastRowNum; row++)
        {
            if (sheet.GetRow(row) != null) //null is when the row only contains empty cells 
            {
                mailids.Add(sheet.GetRow(row).GetCell(0).ToString());
            }
        }
        return mailids;

3 个答案:

答案 0 :(得分:4)

我遇到了同样的问题,我使用Inputstream解决了它。我正在粘贴代码供您参考。

[HttpPost]
    public DataTable PostValues(HttpPostedFileBase file)
    {
       ISheet sheet;
       string filename = Path.GetFileName(Server.MapPath(file.FileName));
       var fileExt = Path.GetExtension(filename);
       if (fileExt == ".xls")
         {
          HSSFWorkbook hssfwb = new HSSFWorkbook(file.InputStream); 
          sheet = hssfwb.GetSheetAt(0);
          }
        else             
          {
          XSSFWorkbook hssfwb = new XSSFWorkbook(file.InputStream); 
          sheet = hssfwb.GetSheetAt(0);
          }

       DataTable table = new DataTable();
       IRow headerRow = sheet.GetRow(0);
       int cellCount = headerRow.LastCellNum;
       for (int i = headerRow.FirstCellNum; i < cellCount; i++)
       {
        DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
        table.Columns.Add(column);
        }
       int rowCount = sheet.LastRowNum;
       for (int i = (sheet.FirstRowNum); i < sheet.LastRowNum; i++)
        {
         IRow row = sheet.GetRow(i);
        DataRow dataRow = table.NewRow();
         for (int j = row.FirstCellNum; j < cellCount; j++)
        {
          if (row.GetCell(j) != null)
            {
            dataRow[j] = row.GetCell(j).ToString();
            }
        }
    table.Rows.Add(dataRow);
                        }
      return table;
        }

答案 1 :(得分:0)

您也可以使用MemoryStream,因此您应该能够获取字节数组repsonse并打开电子表格。我不确定WorkbookFactory是否会从MemoryStream中检测文件类型,因此您可能需要指示用户使用您需要的格式。

答案 2 :(得分:0)

这是我使用MemoryStream从点网核心控制器返回xls而不将其存储为文件的方式。

IWorkbook wb = new HSSFWorkbook();
//Edit workbook object here

MemoryStream m = new MemoryStream();
wb.Write(m);
var byteArray = m.ToArray();
return new FileContentResult(byteArray, "application/vnd.ms-excel");