2014-12-29 3 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를 사용하여 세션 변수를 채울 : 이제 다음 코드가 내가 그 도움이 될 생각을있는 GridViews의 배열을 구축

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

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

을하지만 난 지금을 내보낼 수 없습니다.

 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에 해당한다는 것입니다.

다양한 제 3 자 옵션을 보았지만 인터페이스 안정성을 디버깅하는 결과가 얼마나 신뢰할 수 있는지 알 수 없습니다. MVC에서 핵심 클래스와 옵션을 사용하는 것을 선호합니다.

응용 프로그램이 웹 사이트에서 실행되고 사용자가 링크를 클릭하여 파일을 다운로드합니다.

소매상 테이블은 다음과 같습니다

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

은 따라서 각 워크 시트는 유통 업체에 대한 판매 데이터를해야합니다 및 사용자가 마지막으로 단지 다른 소매 업체를 클릭하고 판매 데이터를 볼 수 있습니다.

누구나 내가 설명한대로 여러 테이블을 내보내는 문제를 해결하는 방법을 알고 있습니까?

+1

웹 서버에서는 Excel COM 구성 요소를 사용하지 않으려합니다. 그들은 거기에서 사용하도록 설계되지 않았기 때문에 많은 오류가 발생할 수 있습니다. 나는 많은 프로젝트에서 [EPPlus] (http://epplus.codeplex.com)를 사용해 왔으며 아주 잘 작동한다. 함께 작업하기가 매우 쉽고 여러 워크 시트를 손쉽게 처리 할 수 ​​있습니다. – krillgar

+0

@krillgar가 말한 바. 나는 일반적으로 내 Excel 요구 사항에 대해 [NPOI] (https://npoi.codeplex.com/)를 사용하며 불만을 제기하지 않았습니다. – Travis

+0

NPOI로 해결했습니다. 나는 나중에 코드를 게시 할 것이다. –

답변

0

nugo를 사용하여 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(); 


    } 
관련 문제