版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_21425067/article/details/65635037
private void ExportDoctoryCase(HttpContext context)
{
//加载模板文件路径
string TempletFileName = context.Server.MapPath("../ExcelTemplate/Template.xls");
HSSFWorkbook wk = null;
using (FileStream fs = File.Open(TempletFileName, FileMode.Open,
FileAccess.Read, FileShare.ReadWrite))
{
//把xls文件读入workbook变量里,之后就可以关闭了
wk = new HSSFWorkbook(fs);
fs.Close();
}
HSSFSheet sheet1 = (HSSFSheet)wk.GetSheetAt(0);
DoctorBLL bll = new DoctorBLL();
DataTable exportTable = bll.GetExportQuestionTable();
if (exportTable != null)
{
int nRow = 2;//开始插入的行(第三行)
string nextFirstTxt = string.Empty;
ICellStyle style1 = SetCellStyle(wk, null, HorizontalAlignment.CENTER);
for (int i = 0; i < exportTable.Rows.Count; i++)
{
IRow row = sheet1.CreateRow(nRow);//创建行
for (int j = 0; j < exportTable.Columns.Count; j++)
{
//创建列并赋值
row.CreateCell(j).SetCellValue(exportTable.Rows[i][j].ToString());
}
//设置Excel行的样式(带边框)
row.GetCell(j).CellStyle = style1;
nRow++;
}
}
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment;filename=问卷导出" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
context.Response.AddHeader("Content-Transfer-Encoding", "binary");
context.Response.ContentType = "application/octet-stream";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
MemoryStream file = new MemoryStream();
wk.Write(file);
context.Response.BinaryWrite(file.GetBuffer());
}
/// <summary>
/// 给Excel添加边框
/// </summary>
public static ICellStyle SetCellStyle(HSSFWorkbook hssfworkbook, IFont font, HorizontalAlignment ha)
{
ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
cellstyle.Alignment = ha;
if (font != null)
{
cellstyle.SetFont(font);
}
//有边框
cellstyle.BorderBottom = BorderStyle.THIN;
cellstyle.BorderLeft = BorderStyle.THIN;
cellstyle.BorderRight = BorderStyle.THIN;
cellstyle.BorderTop = BorderStyle.THIN;
return cellstyle;
}