using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds= bll.GetAllList();
DataTable dt=ds.Tables[0];
OutputExcel(dt, true);
}
/// <summary>
/// 导出Excel
/// </summary>
/// <param name="dt">要导出的数据</param>
/// <param name="isTitle">是否显示表头</param>
public static void OutputExcel(DataTable dt, bool isTitle)
{
Excel.ApplicationClass MyExcel = new Excel.ApplicationClass();
MyExcel.Application.Workbooks.Add(true);
Excel._Worksheet sheet = (Excel._Worksheet)MyExcel.Workbooks[1].Worksheets[1];
sheet.Name = "sheet1";
object Nothing = Missing.Value;
string filepath = @"D:\我的文档\桌面\123XX.xlsx";// 文件路径及文件名;
try
{
if (isTitle)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
MyExcel.Cells[1, i + 1] = dt.Columns[i].ColumnName;//生成表头
}
MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Bold = true;
MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Font.Size = 12;
MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter; //设置对齐方式
MyExcel.get_Range(MyExcel.Cells[1, 1], MyExcel.Cells[1, dt.Columns.Count]).Borders.LineStyle = "1";
}
int Rows = 1;
for (int i = 0; i < dt.Rows.Count; i++)
{
Rows += 1;
for (int j = 0; j < dt.Columns.Count; j++)
{
MyExcel.Cells[Rows, j + 1] = "" + dt.Rows[i][j].ToString();//导入数据
}
MyExcel.get_Range(MyExcel.Cells[Rows, 1], MyExcel.Cells[Rows, dt.Columns.Count]).Borders.LineStyle = "1";
}
sheet.Columns.AutoFit();//自动适应宽度
MyExcel.Visible = true;
sheet.SaveAs(filepath, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing);
}
catch (Exception) { }
finally { }
}