2017-10-17 188 views
1

我正在創建一個MVC控制器動作,其中傳遞給方法的JSON數據將寫入Excel文件。現在,我正在使用基於this blog post示例的數據表中的硬編碼數據測試功能。如何在C#中保存excel文件

這裏是我的代碼:

[HttpPost] 
     public ActionResult ExportData() 
      { 
       Microsoft.Office.Interop.Excel.Application excel; 
       Microsoft.Office.Interop.Excel.Workbook worKbooK; 
       Microsoft.Office.Interop.Excel.Worksheet worKsheeT; 
       Microsoft.Office.Interop.Excel.Range celLrangE; 

       try 
       { 
        excel = new Microsoft.Office.Interop.Excel.Application(); 
        excel.Visible = false; 
        excel.DisplayAlerts = false; 
        worKbooK = excel.Workbooks.Add(Type.Missing); 


        worKsheeT = (Microsoft.Office.Interop.Excel.Worksheet)worKbooK.ActiveSheet; 
        worKsheeT.Name = "StudentRepoertCard"; 

        worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[1, 8]].Merge(); 
        worKsheeT.Cells[1, 1] = "Student Report Card"; 
        worKsheeT.Cells.Font.Size = 15; 


        int rowcount = 2; 

        foreach (DataRow datarow in ExportToExcel().Rows) 
        { 
         rowcount += 1; 
         for (int i = 1; i <= ExportToExcel().Columns.Count; i++) 
         { 

          if (rowcount == 3) 
          { 
           worKsheeT.Cells[2, i] = ExportToExcel().Columns[i - 1].ColumnName; 
           worKsheeT.Cells.Font.Color = System.Drawing.Color.Black; 

          } 

          worKsheeT.Cells[rowcount, i] = datarow[i - 1].ToString(); 

          if (rowcount > 3) 
          { 
           if (i == ExportToExcel().Columns.Count) 
           { 
            if (rowcount % 2 == 0) 
            { 
             celLrangE = worKsheeT.Range[worKsheeT.Cells[rowcount, 1], worKsheeT.Cells[rowcount, ExportToExcel().Columns.Count]]; 
            } 

           } 
          } 

         } 

        } 

        celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[rowcount, ExportToExcel().Columns.Count]]; 
        celLrangE.EntireColumn.AutoFit(); 
        Microsoft.Office.Interop.Excel.Borders border = celLrangE.Borders; 
        border.LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlContinuous; 
        border.Weight = 2d; 

        celLrangE = worKsheeT.Range[worKsheeT.Cells[1, 1], worKsheeT.Cells[2, ExportToExcel().Columns.Count]]; 

        worKbooK.SaveAs("\\root\\test.xlsx"); 
        worKbooK.Close(); 
        excel.Quit(); 

       } 
       catch (Exception ex) 
       { 
        return Json(new { saveSuccess = false }, JsonRequestBehavior.AllowGet); 

       } 
       finally 
       { 
        worKsheeT = null; 
        celLrangE = null; 
        worKbooK = null; 

       } 

       return Json(new { saveSuccess = true }, JsonRequestBehavior.AllowGet); 
      } 
      //private void Form1_Load(object sender, EventArgs e) 
      //{ 
      // dataGridView1.DataSource = ExportToExcel(); 
      //} 
      public System.Data.DataTable ExportToExcel() 
      { 
       System.Data.DataTable table = new System.Data.DataTable(); 
       table.Columns.Add("ID", typeof(int)); 
       table.Columns.Add("Name", typeof(string)); 
       table.Columns.Add("Sex", typeof(string)); 
       table.Columns.Add("Subject1", typeof(int)); 
       table.Columns.Add("Subject2", typeof(int)); 
       table.Columns.Add("Subject3", typeof(int)); 
       table.Columns.Add("Subject4", typeof(int)); 
       table.Columns.Add("Subject5", typeof(int)); 
       table.Columns.Add("Subject6", typeof(int)); 
       table.Rows.Add(1, "Amar", "M", 78, 59, 72, 95, 83, 77); 
       table.Rows.Add(2, "Mohit", "M", 76, 65, 85, 87, 72, 90); 
       table.Rows.Add(3, "Garima", "F", 77, 73, 83, 64, 86, 63); 
       table.Rows.Add(4, "jyoti", "F", 55, 77, 85, 69, 70, 86); 
       table.Rows.Add(5, "Avinash", "M", 87, 73, 69, 75, 67, 81); 
       table.Rows.Add(6, "Devesh", "M", 92, 87, 78, 73, 75, 72); 
       return table; 
      } 

眼下,代碼工作,直到其中發生保存點。出於某種原因,找不到文件位置。我假設文件的名稱必須列在包含文件夾後面的路徑末尾以提供名稱,但是這可能不是指定文件路徑的正確方法。

我真正需要做的是讓用戶選擇文件資源管理器中的文件位置,提供一個名稱,然後保存該文件。既然是這樣,文件路徑將不得不動態提供。我看過很多SO帖子和文章,但我還沒有看到如何做到這一點的明確例子。

如何修改代碼以使用戶能夠指定文件名和路徑?

+0

允許用戶選擇保存文件的位置在哪裏?在服務器的文件夾中?不知道我是否在他們的本地機器上覆蓋 – derloopkat

+0

@derloopkat。他們基本上需要能夠下載excel文件。 – loremIpsum1771

+0

我不是一個MVC人,但與Microsoft.Office.Interop.Excel有過不好的經歷。確保程序運行後沒有EXCEL.exe進程。如果對構建Xml文件的更好方法感興趣,我會使用OpenXml。此[鏈接](https://blogs.msdn.microsoft.com/brian_jones/2010/06/22/writing-large-excel-files-with-the-open-xml-sdk/)「SAX」部分是好教程。 –

回答

2

您不能選擇從瀏覽器保存文件。您需要提供該文件並讓他們下載並將其保存在他們喜歡的位置。

此外,你想要一個生產ASP.NET應用程序的服務器部署到可能沒有安裝Excel的副本(即使它互操作得到一點點混亂恕我直言),所以你可能想使用openXml庫,例如EPPlus。

這將讓你做這樣的事情:

public IActionResult ExportData() 
{ 
    using (var excel = new ExcelPackage()) 
    { 
     var wks = excel.Workbook.Worksheets.Add("StudentReportCard"); 
     wks.Cells[1,1].LoadFromCollection(GetStudentRecords(), PrintHeaders:true); 
     return File(excel.GetAsByteArray(),"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "export.xlsx"); 
    }; 
} 
private static IEnumerable<StudentRecord> GetStudentRecords() 
{ 
    yield return new StudentRecord 
    { 
     Id = 1, 
     Name = "John", 
     Subject = "Maths", 
     Score = 77.9 
    }; 
    yield return new StudentRecord 
    { 
     Id = 2, 
     Name = "Jane", 
     Subject = "Maths", 
     Score = 78.9 
    }; 
    yield return new StudentRecord 
    { 
     Id = 3, 
     Name = "Jo", 
     Subject = "Maths", 
     Score = 99.9 
    }; 
} 

它發送一個文件,這樣用戶名爲「export.xlsx」從他們的瀏覽器保存:

enter image description here

+0

這是一個nuget包,我只在github上看到更新版本。如果它不在nuget上,有沒有其他庫可以做到這一點,你會推薦? – loremIpsum1771

+0

是的,它是一個nuget包:https://www.nuget.org/packages/EPPlus/(或者,如果您使用的是aspnet核心,則爲非官方端口:https://www.nuget.org/packages/EPPlus.core /) –

+0

也請嘗試https://www.easyxls.com/net-excel-library –