protected void Page_Load(object sender, EventArgs e)
{
string strSql = "SELECT TRADE_DATE [Date],TOPEN [Open],Thigh High,tlow [Low] FROM DAY_QUOTATION where SEC_CODE='1' and TRADE_DATE>='20070411' order by TRADE_DATE desc"; //Sql语句
DataSet ds = SqlHandle.ExecuteReturnDataSet(CommandType.Text, strSql, null);
xlsGridview(ds, "data");//调用xlsGridview方法生成Excel报表
}
/// <summary>
/// 绑定数据库生成XLS报表
/// </summary>
/// <param name="ds">获取DataSet数据集</param>
/// <param name="xlsName">报表表名</param>
private void xlsGridview(DataSet ds, string xlsName)
{
XlsDocument xls = new XlsDocument();
int rowIndex = 1;
int colIndex = 0;
System.Data.DataTable table = ds.Tables[0];
Worksheet sheet = xls.Workbook.Worksheets.AddNamed("sheet");//状态栏标题名称
Cells cells = sheet.Cells;
foreach (DataColumn col in table.Columns)
{
colIndex++;
//sheet.Cells.AddValueCell(1,colIndex,col.ColumnName);//添加XLS标题行
cells.AddValueCell(1, colIndex,col.ColumnName);
}
foreach (DataRow row in table.Rows)
{
rowIndex++;
colIndex = 0;
foreach (DataColumn col in table.Columns)
{
colIndex++;
//sheet.Cells.AddValueCell(rowIndex, colIndex, row[col.ColumnName].ToString());//将数据添加到xls表格里
Cell cell= cells.AddValueCell(rowIndex, colIndex, Convert.ToDouble(row[col.ColumnName].ToString()));//转换为数字型
//如果你数据库里的数据都是数字的话 最好转换一下,不然导入到Excel里是以字符串形式显示。
cell.Font.FontFamily = FontFamilies.Roman; //字体
cell.Font.Bold = true; //字体为粗体
}
}
xls.Send();
}