第一:添加一个程序集引用
第二:在代码中引用 using Microsoft.Office.Interop.Excel
第三:在事件中引用如下方法
protected void ExportExcel(System.Data.DataTable dt)
{
int s = 0;
if (dt == null || dt.Rows.Count == 0) return;
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
if (xlApp == null)
{
return;
}
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];
Microsoft.Office.Interop.Excel.Range range;
long totalCount = dt.Rows.Count;
long rowRead = 0;
float percent = 0;
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Columns.Add("车牌号", typeof(string));
dataTable.Columns.Add("车辆类型", typeof(string));
dataTable.Columns.Add("车辆编号", typeof(string));
dataTable.Columns.Add("车队", typeof(string));
dataTable.Columns.Add("荷载量", typeof(string));
dataTable.Columns.Add("卡号描述", typeof(string));
dataTable.Columns.Add("车长(米)", typeof(string));
dataTable.Columns.Add("车宽(米)", typeof(string));
dataTable.Columns.Add("车高(米)", typeof(string));
dataTable.Columns.Add("备注", typeof(string));
dataTable.Columns.Add("皮重", typeof(string));
dataTable.Columns.Add("司机手机", typeof(string));
foreach (DataRow dr in dt.Rows)
{
s++;
DataRow row = dataTable.NewRow();
row["车牌号"] = dr["carNo"].ToString();
DataRow[] drName =this.MyCarTypeDataSet.TRM_CarType.Select("typeID=" + dr["typeID"].ToString());
//string str = drName[0].ItemArray[1].ToString();
if (drName != null && drName.Length > 0)
row["车辆类型"] = drName[0].ItemArray[1].ToString();
else
row["车辆类型"] ="";
row["车辆编号"] = dr["carNumber"].ToString();
row["车队"] = dr["providerName"].ToString();
row["荷载量"] = dr["payload"].ToString();
row["卡号描述"] = dr["bindingContent"].ToString();
row["车长(米)"] = dr["length"].ToString();
row["车宽(米)"] = dr["width"].ToString();
row["车高(米)"] = dr["high"].ToString();
row["备注"] = dr["memo"].ToString();
row["皮重"] = dr["carWeight"].ToString();
row["司机手机"] = dr["driverPhone"].ToString();
dataTable.Rows.Add(row);
}
for (int i = 0; i < dataTable.Columns.Count; i++)
{
worksheet.Cells[1, i + 1] = dataTable.Columns[i].ColumnName;
range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];
range.Interior.ColorIndex = 15;
range.Font.Bold = true;
}
for (int r = 0; r < dataTable.Rows.Count; r++)
{
for (int i = 0; i < dataTable.Columns.Count; i++)
{
worksheet.Cells[r + 2, i + 1] = dataTable.Rows[r][i].ToString();
}
rowRead++;
percent = ((float)(100 * rowRead)) / totalCount;
}
xlApp.Visible = true;
}