Asp.net & Aspose.cells 导出

时间:2021-06-23 06:12:52
   protected void btnExport_Click(object sender, EventArgs e)
{
DataTable tbBooks = (DataTable)Session["Books"];
if (tbBooks == null)
{
return;
} try
{
Workbook newWorkBook = NewExcel();
Aspose.Cells.Worksheet newSheet = newWorkBook.Worksheets[];
Cells newCells = newSheet.Cells; if (tbBooks != null)
{
for (int i = ; i < tbBooks.Rows.Count; i++)
{ for (int j = ; j < tbBooks.Columns.Count; j++)
{ newCells[i+1, j].PutValue(tbBooks.Rows[i][j].ToString());
}
}
}
newWorkBook.Save("result.xlsx", Aspose.Cells.FileFormatType.Excel97To2003, Aspose.Cells.SaveType.OpenInExcel, Response);
}
catch (Exception ex)
{
MessageBox.Show(this, "导出产品信息库出错,详细错误为:" + ex.Message);
}
} public Workbook NewExcel()
{
DataTable table = (DataTable)Session["Books"];
Workbook newWorkBook = new Workbook();
Aspose.Cells.Worksheet sheet = newWorkBook.Worksheets[];
Cells cells = sheet.Cells; Aspose.Cells.Style style = newWorkBook.Styles[newWorkBook.Styles.Add()];//新增样式
style.HorizontalAlignment = TextAlignmentType.Center;
style.Font.Size = ;
style.Font.Color = System.Drawing.Color.Red;
cells.SetRowHeight(, ); for (int i = ; i < table.Columns.Count; i++)
{
cells[, i].PutValue(table.Columns[i].ColumnName);
cells[, i].SetStyle(style);
cells.SetColumnWidthPixel(i, );
}
return newWorkBook;
}