这里用到第三方库Microsoft.Office.Interop.Excel,添加该引用后,鼠标右键该引用查看属性,将嵌入互操作类型true改为fase,电脑上需要下载office2013或者更高版本
private void btnliving_Click(object sender, EventArgs e)
{
DataTabletoExcel1(dt, DateTime.Now.Ticks + ".xlsx");
}
public void DataTabletoExcel1(System.Data.DataTable tmpDataTable, string strFileName)
{
///先得到datatable的行数
int rowNum = tmpDataTable.Rows.Count;
///列数
int columnNum = tmpDataTable.Columns.Count;
///声明一个应用程序类实例
Application xlApp = new ApplicationClass();
//xlApp.DefaultFilePath = ""; ///默认文件路径,将其设置路径后发现没什么变化。导出excel的路径还是在参数strFileName里设置
//xlApp.DisplayAlerts = true;
//xlApp.SheetsInNewWorkbook = 1;///返回或设置 Microsoft Excel 自动插入到新工作簿中的工作表数目。Long 类型,可读写。设置为2之后没发现什么区别
//创建一个新工作簿
Workbook xlBook = xlApp.Workbooks.Add();
///在工作簿中得到sheet。
_Worksheet oSheet = (_Worksheet)xlBook.Worksheets[1];
#region 绘制列
///自定义方法,想sheet中绘制列
RangeBuild(oSheet, "A1", "M1", "xxxxxx报表", true);
RangeBuild(oSheet, "A2", "A3", "序号", true);
RangeBuild(oSheet, "B2", "B3", "日期", false);
RangeBuild(oSheet, "C2", "E2", "二维表头", true);
RangeBuild(oSheet, "C3", "C3", "二维表头", true);
RangeBuild(oSheet, "D3", "D3", "二维表头", true);
RangeBuild(oSheet, "E3", "E3", "二维表头", true);
RangeBuild(oSheet, "F2", "F2", "二维表头", true);
RangeBuild(oSheet, "F3", "F3", "二维表头", true);
RangeBuild(oSheet, "G2", "G2", "二维表头", true);
RangeBuild(oSheet, "G3", "G3", "二维表头", true);
RangeBuild(oSheet, "H2", "J2", "二维表头", true);
RangeBuild(oSheet, "H3", "H3", "二维表头", true);
RangeBuild(oSheet, "I3", "I3", "二维表头", true);
RangeBuild(oSheet, "J3", "J3", "二维表头", true);
RangeBuild(oSheet, "K2", "M2", "二维表头", true);
RangeBuild(oSheet, "K3", "K3", "二维表头", true);
RangeBuild(oSheet, "L3", "L3", "二维表头", true);
RangeBuild(oSheet, "M3", "M3", "二维表头", true);
#endregion
//将DataTable中的数据导入Excel中
for (int i = 0; i < rowNum; i++)
{
for (int j = 0; j < columnNum; j++)
{
///excel中的列是从1开始的
xlApp.Cells[i + 4, j + 1] = tmpDataTable.Rows[i][j].ToString();
}
}
///保存,路径一块穿进去。否则回到一个很奇妙的地方,貌似是system32里 temp下....
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "xlsx|*.xlsx";
sfd.FileName = "xxxxxx报表" + DateTime.Now.ToString("yyyyMMddHHmmss");
if (sfd.ShowDialog() == DialogResult.OK)
{
oSheet.SaveAs(sfd.FileName);
}
else
{
return;
}
Process.Start(sfd.FileName);
}
private static void RangeBuild(_Worksheet oSheet, string startcell, string endcell, string value, bool isAutoWidth)
{
///创建一个区域对象。第一个参数是开始格子号,第二个参数是终止格子号。比如选中A1——D3这个区域。
Range range = (Range)oSheet.get_Range(startcell, endcell);
///合并方法,0的时候直接合并为一个单元格
range.Merge(0);
///合并单元格之后,设置其中的文本
range.Value = value;
//横向居中
range.HorizontalAlignment = XlVAlign.xlVAlignCenter;
///字体大小
range.Font.Size = 10;
///字体
range.Font.Name = "黑体";
///行高
range.RowHeight = 24;
if (isAutoWidth)
{
//自动调整列宽
range.EntireColumn.AutoFit();
}
else
{
range.ColumnWidth = 20;
}
//填充颜色
range.Interior.ColorIndex = 20;
//设置单元格边框的粗细
range.Cells.Borders.LineStyle = 1;
}