2014-12-29 109 views
0

我已经成功地将数据从gridview导出到Excel作为单个工作表,但我想添加多个工作表。我搜索了一下,并尝试了几个选项,但没有任何工作,但我越来越接近。我认为这只是几行代码的问题。现在,我有以下代码:在MVC中将数据导出到Excel

public ActionResult Download() 
    { 
     if (Session["BP"] != null) 
     { 
      return new DownloadFileActionResult((GridView)Session["BP"], "BestPrices.xls"); 
     } 
     else 
     { 
      return new JavaScriptResult(); 
     } 
    } 

我填充使用确定年代和GridView会话变量:

GridView gv = new GridView(); 
     gv.DataSource = gridTable; 

     gv.DataBind(); 
    // Session["BP"] = myGridViews; 
     Session["BP"] = g; 

我已经建立了GridView的思想,这将有助于数组,但我不能出口,现在。

 GridView[] g = new GridView[retailerTables.Count]; 
     int n = 0; 
     foreach (string key in keys) 
     { 
      myGridViews[n] = retailerTables[key]; 
      g[n] = new GridView(); 
      g[n].DataSource = retailerTables[key]; 
      g[n].DataBind(); 
      n++; 


     } 

我的基本想法是,excel文件中的每个工作表都对应一个gridview。

我见过各种第三方选项,但我不知道它们有多可靠,如果我最终会调试接口错误。我更喜欢在MVC中使用核心类和选项。

该应用程序在网站上运行,用户将点击链接下载该文件。

零售商表是:

Dictionary<string, DataTable> retailerTables= new Dictionary<string, DataTable>(); 

因此,每个工作都会有销售数据,零售商和用户终于可以只需点击不同的零售商和看到的销售数据。

有没有人知道如何解决这个问题,以导出多个表格,如我所概述的。

+1

您不想在Web服务器上使用Excel COM组件。它们不是为那里的使用而设计的,而且可能会发生大量的错误。我在很多项目中使用过[EPPlus](http://epplus.codeplex.com),并且它工作得很好。使用起来非常简单,并且轻松处理多个工作表。 – krillgar

+0

@krillgar说了什么。我通常使用[NPOI](https://npoi.codeplex.com/)来满足我的Excel需求,并且没有投诉。 – Travis

+0

我解决了使用NPOI。我稍后会发布代码。 –

回答

0

我用nuget安装npoi。我用于使用语句:

using NPOI.SS.UserModel; 
using NPOI.HSSF.UserModel; 
using NPOI.HSSF.Util; 


public void DataTablesToXls(Dictionary<string, DataTable> retailerTables, String filename, String allName) 
    { 

     var keys = new List<string>(retailerTables.Keys); 
     HSSFWorkbook xlsWorkBook = new HSSFWorkbook(); 
     IFont hlink_font = xlsWorkBook.CreateFont(); 
     ICellStyle hlink_style = xlsWorkBook.CreateCellStyle(); 

     HSSFFont bestpriceFont = (HSSFFont)xlsWorkBook.CreateFont(); 
     HSSFCellStyle bestpriceStyle = (HSSFCellStyle)xlsWorkBook.CreateCellStyle(); 
     bestpriceFont.Color = HSSFColor.Blue.Index; 
     bestpriceStyle.FillForegroundColor = HSSFColor.Blue.Index; 
     bestpriceStyle.SetFont(bestpriceFont); 


     HSSFFont priceFont = (HSSFFont)xlsWorkBook.CreateFont(); 
     HSSFCellStyle priceStyle = (HSSFCellStyle)xlsWorkBook.CreateCellStyle(); 
     priceFont.Color = HSSFColor.Red.Index; 
     bestpriceStyle.FillForegroundColor = HSSFColor.Red.Index; 
     priceStyle.SetFont(priceFont); 

     HSSFFont matchFont = (HSSFFont)xlsWorkBook.CreateFont(); 
     HSSFCellStyle matchStyle = (HSSFCellStyle)xlsWorkBook.CreateCellStyle(); 
     matchFont.Color = HSSFColor.Green.Index; 
     matchStyle.FillForegroundColor = HSSFColor.Green.Index; 
     matchStyle.SetFont(matchFont); 

     HSSFFont ordinaryFont = (HSSFFont)xlsWorkBook.CreateFont(); 
     HSSFCellStyle ordinaryStyle = (HSSFCellStyle)xlsWorkBook.CreateCellStyle(); 
     ordinaryFont.Color = HSSFColor.Black.Index; 
     ordinaryStyle.FillForegroundColor = HSSFColor.Black.Index; 
     ordinaryStyle.SetFont(ordinaryFont); 
     Dictionary<string, HSSFCellStyle> fonts = new Dictionary<string,HSSFCellStyle>(); 
     fonts.Add("best", bestpriceStyle); 
     fonts.Add("price", priceStyle); 
     fonts.Add("match", matchStyle); 
     fonts.Add("ordinary", ordinaryStyle); 


     string keyFont = "ordinary"; 
     foreach (string key in keys) 
     { 
      if (!(@key.Equals(allName))) 
      { 


       DataTable dt = retailerTables[key]; 


       ISheet retailerWorkSheet = xlsWorkBook.CreateSheet(@key); 


       IRow header = retailerWorkSheet.CreateRow(0); 

       int rcount = 0; 
       int colCount = 0; 

       colCount = 0; 
       IRow rheader = retailerWorkSheet.CreateRow(rcount); 
       foreach (DataColumn column in dt.Columns) 
       { 
        // Console.WriteLine(row[column]); 

        ICell c = rheader.CreateCell(colCount); 
        // c.SetCellValue(dt.Rows[0][column].ToString()); 
        c.SetCellValue(@column.ToString()); 

        colCount++; 
       } 

       Boolean matchRow = false; 
       rcount++; 
       foreach (DataRow row in dt.Rows) 
       { 
        colCount = 0; 
        IRow r = retailerWorkSheet.CreateRow(rcount); 

        Boolean bestpriceRow = false; 
        if (allName.Equals("all")) 
        { 
         if (row[dt.Columns[2]].Equals(@key)) // handling all data 
         { 
          bestpriceRow = true; 
          keyFont = "best"; 
         } else { 
          keyFont = "price"; 
         } 
        } 

        foreach (DataColumn column in dt.Columns) 
        { 
         // Console.WriteLine(row[column]); 

         HSSFCell c = (HSSFCell)r.CreateCell(colCount); 
         // retailerWorkSheet.AutoSizeColumn(column.Ordinal); 


         String rowVal = row[column].ToString(); 
         if (allName.Equals("none")) { 
          if (row[dt.Columns[3]].Equals(rowVal)) // handling all data 
          { 
           bestpriceRow = false; // show in red 
           matchRow = true; 
           keyFont = "match"; 
          } 
          else 
          { 
           bestpriceRow = false; 
           matchRow = false; 
           keyFont="ordinary"; 
          } 


         } 
         //  if (@key.Equals("all")) 
         //  { 
         //  hlink_font.Color = HSSFColor.Black.Index; 
         //  hlink_style.SetFont(hlink_font); 

         //  } else { 
        //  if (rowVal.Equals(@key)) 
        //  { 
        //   bestpriceRow = true; 
        //  } 

         //  } 


         if (rowVal != null) 
         { 
          if (rowVal.IndexOf("=HYPERLINK") != -1) 
          { 
           string[] celldata = new string[2]; 
           celldata = getCellData(rowVal); 

           // rowVal.IndexOf("\""); 

           // rowVal = rowVal.Replace("=HYPERLINK", ""); 
           //rowVal = rowVal.Replace("(", ""); 
           // rowVal = rowVal.Replace(")", ""); 
           // rowVal = rowVal.Replace("\",\"", ";"); 
          // string[] words = rowVal.Split(';'); 
           if (celldata!=null) 
           { 
           //  string cellValue = words[1]; 
            string cellLink = celldata[0]; 
           //  cellValue = cellValue.Replace("\"", ""); 
           // cellLink = cellLink.Replace("\"", ""); 
            string cellValue = celldata[1]; 
            HSSFHyperlink link = new HSSFHyperlink(HyperlinkType.Url); 
            link.Address = cellLink; 
            c.SetCellValue(cellValue); 
            c.Hyperlink = (link); 
            c.CellStyle= fonts[@keyFont]; 
           /*  if (bestpriceRow) 
            { 

             c.CellStyle = bestpriceStyle; 
            } 
            else 
            { 
             if (matchRow) 
             { 
              c.CellStyle = matchStyle; 
             } 
             else 
             { 
              c.CellStyle = priceStyle; 
             } 
            } */ 

           } 

          } 
          else 
          { 

           c.SetCellValue(row[column].ToString()); 
            c.CellStyle= fonts[@keyFont]; 
          /* if (bestpriceRow) 
           { 

            c.CellStyle = bestpriceStyle; 
           } 
           else 
           { 
            if (matchRow) 
            { 
             c.CellStyle = matchStyle; 
            } 
            else 
            { 
             c.CellStyle = priceStyle; 
            } 
           } */ 

          } 
         } 
         else 
         { 

          c.SetCellValue(row[column].ToString()); 
          c.CellStyle= fonts[@keyFont]; 
          /* if (bestpriceRow) 
          { 

           c.CellStyle = bestpriceStyle; 
          } 
          else 
          { 
           if (matchRow) 
           { 
            c.CellStyle = matchStyle; 
           } 
           else 
           { 
            c.CellStyle = priceStyle; 
           } 
          } */ 

         } 

         colCount++; 
        } 
        rcount++; 
       } 


      } 

      // retailerTables[key] 
     } 

     string folderPath = Server.MapPath("~/Content/data"); 
     string datafile = Path.Combine(folderPath, filename); 


     FileStream file = new FileStream(datafile, FileMode.CreateNew); 
     xlsWorkBook.Write(file); 
     file.Close(); 


    }