?
首先在官網去下載NPOI,把dll引用到項目中,然后獲取列表調用下面的方法就可以導出
后臺代碼:
/// <summary>
/// NPOI導出Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="fileName"></param>
public static void ExportExcel(DataTable dt, string fileName = "")
{
//生成Excel
IWorkbook book = BuildWorkbook(dt);
//web 下載
if (fileName == "")
fileName = string.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
fileName = fileName.Trim();
string ext = Path.GetExtension(fileName);
if (ext.ToLower() == ".xls" || ext.ToLower() == ".xlsx")
fileName = fileName.Replace(ext, string.Empty);
HttpResponse httpResponse = HttpContext.Current.Response;
httpResponse.Clear();
httpResponse.Buffer = true;
httpResponse.Charset = Encoding.UTF8.BodyName;
httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
httpResponse.ContentEncoding = Encoding.UTF8;
httpResponse.ContentType = "application/vnd.ms-excel; charset=UTF-8";
book.Write(httpResponse.OutputStream);
httpResponse.End();
}
//高版本
public static XSSFWorkbook BuildWorkbook(DataTable dt)
{
var book = new XSSFWorkbook();
ISheet sheet = book.CreateSheet("機構聯系信息");
//Data Rows
NPOI.SS.UserModel.IRow row1 = sheet.CreateRow(0);
row1.CreateCell(0).SetCellValue("機構名稱");
row1.CreateCell(1).SetCellValue("聯系人姓名");
row1.CreateCell(2).SetCellValue("辦公電話");
row1.CreateCell(3).SetCellValue("手機號");
row1.CreateCell(4).SetCellValue("郵箱");
row1.CreateCell(5).SetCellValue("傳真號");
row1.CreateCell(6).SetCellValue("QQ號碼");
row1.CreateCell(7).SetCellValue("微信號碼");
row1.CreateCell(8).SetCellValue("地址");
row1.CreateCell(9).SetCellValue("郵編");
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow drow = sheet.CreateRow(i+1);
for (int j = 0; j < dt.Columns.Count; j++)
{
ICell cell = drow.CreateCell(j, CellType.String);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
//自動列寬
for (int i = 0; i <= dt.Columns.Count; i++)
sheet.AutoSizeColumn(i, true);
return book;
}
?
前臺代碼:
//導出
function exportExcel(type) {
searchName = $("#txt_name").val();
if (type == "0") {
if (total == 0) {
layerAlert("沒有數據可以導出", 1);
return;
}
}
else {
if (total2 == 0) {
layerAlert("沒有數據可以導出", 1);
return;
}
}
var form = $("<form>"); //定義一個form表單
form.attr('style', 'display:none'); //在form表單中添加查詢參數
form.attr('target', '');
form.attr('method', 'post');
var num = $("#hidNum").val();
if (type == "0") {
form.attr('action', "ContactAction.ashx?action=ExportLeaderExcel&name=" + searchName);
}
$('body').append(form); //將表單放置在web中
form.submit(); //表單提交
}