码迷,mamicode.com
首页 > 其他好文 > 详细

NPOI导出Excel合并表头写入公式

时间:2016-12-08 02:01:04      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:out   居中   error   水平对齐   use   value   cte   公式   ble   

protected void Btn1_Click(object sender, EventArgs e)
{
//建立空白工作簿
IWorkbook workbook = new HSSFWorkbook();
//在工作簿中:建立空白工作表
ISheet sheet = workbook.CreateSheet();
#region
//在工作表中:建立行,参数为行号,从0计
IRow row = sheet.CreateRow(0);
//在行中:建立单元格,参数为列号,从0计
ICell cell = row.CreateCell(0);
//设置单元格内容
cell.SetCellValue("实习鉴定表");
ICell cell2 = row.CreateCell(1);
cell2.SetCellValue("表格2");
ICell cell3 = row.CreateCell(3);
cell3.SetCellValue("表格3");

ICellStyle style = workbook.CreateCellStyle();
//设置单元格的样式:水平对齐居中
style.Alignment = HorizontalAlignment.CENTER;
//新建一个字体样式对象
IFont font = workbook.CreateFont();
//设置字体加粗样式
font.Boldweight = short.MaxValue;
//使用SetFont方法将字体样式添加到单元格样式中
style.SetFont(font);
//将新的样式赋给单元格
cell.CellStyle = style;

//设置单元格的高度
row.Height = 30 * 20;
//设置单元格的宽度
sheet.SetColumnWidth(0, 30 * 256);

//设置一个合并单元格区域,使用上下左右定义CellRangeAddress区域
//CellRangeAddress四个参数为:起始行,结束行,起始列,结束列
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 1, 2));
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 3, 5));
#endregion

string[] arr = GetSql();
DataSet ds = new DataSet();
SqlHelper.ExecuteSQL(arr[1], "EU_Users", 1, 10, out ds);

try
{
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow rowN = sheet.CreateRow(i + 1);
ICell cellN = null;
for (int j = 0; j <= 50; j++)
{
cellN = rowN.CreateCell(j);
cellN.SetCellValue(dt.Rows[i][j] + "");
}
}
}
catch (Exception ex)
{
string error= ex.Message;
}

 


//通过Cell的CellFormula向单元格中写入公式
//注:直接写公式内容即可,不需要在最前加‘=‘
//ICell cell2 = sheet.CreateRow(1).CreateCell(0);
//cell2.CellFormula = "HYPERLINK(\"测试图片.jpg\",\"测试图片.jpg\")";

using (FileStream fs = new FileStream(@"D:\生成效果.xls", FileMode.Create, FileAccess.Write))
{
workbook.Write(fs);
}
}

NPOI导出Excel合并表头写入公式

标签:out   居中   error   水平对齐   use   value   cte   公式   ble   

原文地址:http://www.cnblogs.com/LastDance/p/6143111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!