我想使用mvc.Here使用我使用的东西,通过浏览器'将sql表数据导出到客户端PC上的excel文件中:
public class ManagementController : Controller
{
public void ExportitemToExcel()
{
try
{
dt = SqlHelper.LoadTable("SM_GetAllItems", sql);
if (dt != null && dt.Rows.Count > 0)
{
ExportToExcel(dt);
}
}
catch
{ throw; }
}
这是导出到excel方法:
private void ExportToExcel(DataTable dt)
{
Microsoft.Office.Interop.Excel.Application excel;
Microsoft.Office.Interop.Excel.Workbook worKbooK;
Microsoft.Office.Interop.Excel.Worksheet worKsheeT;
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 = "Inventory";
//Create an Excel workbook instance and open it from the predefined location
// Excel.Workbook excelWorkBook = excel.Workbooks.Open(@"E:\Org.xlsx");
// Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
//excelWorkSheet.Name = dt.TableName;
for (int i = 1; i < dt.Columns.Count + 1; i++)
{
worKsheeT.Cells[1, i] = dt.Columns[i - 1].ColumnName;
}
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
worKsheeT.Cells[j + 2, k + 1] = dt.Rows[j].ItemArray[k].ToString();
}
}
string fastExportFilePath = "C:/" + "Inventory" + ".xlsx";
if (System.IO.File.Exists(fastExportFilePath))
{
System.IO.File.Delete(fastExportFilePath);
}
worKbooK.SaveAs(fastExportFilePath);
worKbooK.Close();
excel.Quit();
这会创建文件,但不是通过浏览器。
答案 0 :(得分:0)
您无法将Excel直接保存到客户端的电脑上。您可以做的是将excel保存到服务器并与客户共享以进行下载。
您可以修改ExportToExcel方法以返回用于打开Excel文件的生成文件名。
private string ExportToExcel(DataTable dt)
{
//your code goes here
return fastExportFilePath
}
的Javascript
$(document).ready(function () {
//Check if the hidden field has a value. (Excel was generated)
if ($('#hdnFileName').val() != '')
{
var url = "Full path to your file" + $('#hdnFileName').val();
window.location.assign(url)
}
});