2014-12-29 155 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(); 


    }