using Aspose.Cells;
public void btnExcel_Click(object sender, EventArgs e)
{
Workbook workbook = new Workbook();
workbook.Worksheets.Clear();
workbook.Worksheets.Add("sheet1");
Worksheet worksheet = workbook.Worksheets[0];
Cells cells = worksheet.Cells;
MergeCell(cells, "内容", int, int, int, int, workbook);//如果需要合并单元格加上这句话 cells.Merge(从第几行开始,从第几列开始 ,合并几行 ,合并几列 );
--------------------合并单元格的循环-------------------------
for (int i = 0; i < 一共有几列; i++)
{
for (int j = 0; j <= 共合并了行; j++)
{
cells[j, i].SetStyle(CreateStyle(workbook));
cells.Columns[i].Width = 15;//设置每个单元格的宽
}
}
--------------------------------------------------------------------
-------------------不合并用的循环---------------------------------
for (int i = 0; i < 23; i++)
{
cells[0, i].SetStyle(CreateStyle(workbook));
cells.Columns[i].Width = 15;//设置每个单元格的宽
}
----------------------------------------------------------------------
int rowIndex =数据开始所在行的索引;
IList<> 数据源集合= ;
foreach (var item in 数据源集合)
{
MergeCell(cells, item.数据1, rowIndex, 0, 1, 1, workbook);
MergeCell(cells, item.数据2, rowIndex, 1, 1, 1, workbook);
rowIndex++;
}
string exportFileName = HttpUtility.UrlEncode("生成excel的名字" + DateTime.Now.ToString("yyyyMMddHHmm") + ".xlsx");
workbook.Save(exportFileName, FileFormatType.Xlsx, SaveType.OpenInExcel, Response);
Response.End();
}
-------- 复制即可用
/// <summary>
/// 合并单元格
/// </summary>
/// <param name="cells">单元格</param>
/// <param name="value">显示的值</param>
/// <param name="rBegin">第几行开始</param>
/// <param name="cBegin">第几列开始</param>
/// <param name="rCount">合并多少行</param>
/// <param name="cCount">合并多少列</param>
public void MergeCell(Cells cells, string value, int rBegin, int cBegin, int rCount, int cCount, Workbook workbook)
{
cells.Merge(rBegin, cBegin, rCount, cCount);
cells[rBegin, cBegin].PutValue(value);
cells[rBegin, cBegin].SetStyle(CreateStyle(workbook));
}
/// <summary>
/// 设置样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
private Aspose.Cells.Style CreateStyle(Workbook workbook)
{
Aspose.Cells.Style style = workbook.Styles[workbook.Styles.Add()];
style.HorizontalAlignment = TextAlignmentType.Center;
style.VerticalAlignment = TextAlignmentType.Center;
style.IsTextWrapped = true;
style.Font.IsBold = true;
style.Font.Size = 11;
style.Font.Color = System.Drawing.Color.Black;
style.Pattern = BackgroundType.Solid;
style.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;
style.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
return style;
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交