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);
--------------------合并单元格的循环-------------------------
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();
}
-------- 复制即可用
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));
}
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;
}