public void ToExcel(DataSet ds, string strFileName)
{
XlsDocument xls = new XlsDocument();
xls.FileName = strFileName;
foreach (DataTable dtSource in ds.Tables)
{
string sheetName = dtSource.TableName;
Worksheet sheet = xls.Workbook.Worksheets.Add(dtSource.TableName);//状态栏标题名称
Cells cells = sheet.Cells;
foreach (DataColumn col in dtSource.Columns)
{
Cell cell = cells.Add(1, col.Ordinal + 1, col.ColumnName);
cell.Font.FontFamily = FontFamilies.Roman; //字体
cell.Font.Bold = true; //字体为粗体
}
#region 填充内容
XF dateStyle = xls.NewXF();
dateStyle.Format = "yyyy-mm-dd";
for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < dtSource.Columns.Count; j++)
{
int rowIndex = i + 2;
int colIndex = j + 1;
string drValue = dtSource.Rows[i][j].ToString();
switch (dtSource.Rows[i][j].GetType().ToString())
{
case "System.String"://字符串类型
cells.Add(rowIndex, colIndex, drValue);
break;
case "System.DateTime"://日期类型
DateTime dateV;
DateTime.TryParse(drValue, out dateV);
cells.Add(rowIndex, colIndex, dateV, dateStyle);
break;
case "System.Boolean"://布尔型
bool boolV = false;
bool.TryParse(drValue, out boolV);
cells.Add(rowIndex, colIndex, boolV);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = 0;
int.TryParse(drValue, out intV);
cells.Add(rowIndex, colIndex, intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
double.TryParse(drValue, out doubV);
cells.Add(rowIndex, colIndex, doubV);
break;
case "System.DBNull"://空值处理
cells.Add(rowIndex, colIndex, null);
break;
default:
cells.Add(rowIndex, colIndex, null);
break;
}
}
}
#endregion
}
xls.FileName = strFileName;
//xls.Save();
xls.Send(XlsDocument.SendMethods.Inline);
}