【MVC】 页面导出 WORD, EXCEL
前端 js
function output() {
var para = new Object();
para.html = getHtml("outputData");
para.type = "excel";
getAjaxText("/Test/SaveData", para, function (data) {
if (data != "") {
openWindow(stringFormat("/Test/Output?id={0}&type={1}&title={2}", data, para.type, "ceshi"));
}
});
}
后端 Action
public ActionResult Output(string id, string title, string type)
{
var path = GetFilePath(id, type);
if (!System.IO.File.Exists(path))
{
return Redirect("/Error/Index");
}
Response.ContentEncoding = Encoding.GetEncoding("gb2312");
var byteArray = System.IO.File.ReadAllBytes(path);
return File(byteArray, "application/ms-" + type, title + GetType(type));
} [ValidateInput(false)]
public ActionResult SaveData(string html, string type)
{
var sb = new StringBuilder();
sb.Append("<!DOCTYPE html>");
sb.Append("<body>");
sb.Append(html);
sb.Append("</body>");
var byteArray = Encoding.Default.GetBytes(sb.ToString());
var guid = Guid.NewGuid();
System.IO.File.WriteAllBytes(GetFilePath(guid.ToString(), type), byteArray);
return Content(guid.ToString());
} private static string GetType(string type)
{
if (type.ToLower().Trim() == "word")
{
return ".doc";
}
return ".xls";
}
MS Excel 导出
public class ExcelHelper
{
public static void ExportExcel(DataTable dt, bool noColumn = false)
{
if (dt == null || dt.Rows.Count == 0) return; var xlApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks; Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
if (!noColumn)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
var range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
} for (int r = 0; r < dt.Rows.Count; r++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dt.Rows[r][i].ToString();
}
}
xlApp.Visible = true;
}
}