c# 与ajax 结合使用 实现excel 导出
js 代码
$.ajax({
type: "Post",
url: "/RMBase/SysReport/Housingresources_List.aspx/ExportToExcel",
contentType:"application/json;charset=utf-8",
success: function (msg) {
alert("成功导出数据");
},
error: function (err)
{
alert("导出过程中发生错误");
}
});
c#代码
[WebMethod]
public static string ExportToExcel()
{
if (dtReport != null)
{
Microsoft.Office.Interop.Excel._Application xlApp = null;
try
{
xlApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
}
catch (Exception ex)
{
throw ex;
}
if(xlApp != null)
{
try
{
Microsoft.Office.Interop.Excel.Workbook xlBook = xlApp.Workbooks.Add(true);
object oMissing = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Worksheet xlSheet = null;
xlSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlBook.Worksheets[1];
xlSheet.Name = "table";
int colCount = dtReport.Columns.Count;
int rowCount = dtReport.Rows.Count;
//列名
xlSheet.Cells[2, 1] = "街道";
xlSheet.Cells[2, 2] = "小区";
xlSheet.Cells[2, 3] = "楼栋";
xlSheet.Cells[2, 4] = "室号";
xlSheet.Cells[2, 5] = "所属工程";
xlSheet.Cells[2, 6] = "面积";
xlSheet.Cells[2, 7] = "对应车库";
xlSheet.Cells[2, 8] = "阁楼面积";
xlSheet.Cells[2, 9] = "拆迁户姓名";
xlSheet.Cells[2, 10] = "身份证";
xlSheet.Cells[2, 11] = "联系方式";
for (int i = 1; i < 12;i++ )
{
xlSheet.get_Range(xlSheet.Cells[2, i], xlSheet.Cells[2, i]).Font.Bold = true;
xlSheet.get_Range(xlSheet.Cells[2, i], xlSheet.Cells[2, i]).Font.Size = "10";
}
for (int i = 0; i < rowCount; i++)
{
for (int j = 1; j < colCount; j++)
{
xlSheet.Cells[i+3, j] = dtReport.Rows[i][j-1].ToString();
}
}
xlSheet.Cells.EntireColumn.AutoFit();
xlApp.DisplayAlerts = false;
xlApp.Visible = true;
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
}
return "";
}