[英]How to save an excel file in C#
我正在創建一個MVC控制器操作,在該操作中,傳遞給該方法的JSON數據將被寫入到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帖子和文章,但沒有看到一個清晰的示例。
如何修改代碼以使用戶能夠指定文件名和路徑?
您不能選擇從他們的瀏覽器中保存文件。 您需要提供文件,然后讓他們下載並保存到他們喜歡的位置。
此外,您要部署到生產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”的文件供用戶從瀏覽器保存:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.