自用datatable导出到excel
//设置程序运行语言
System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
//创建Application
Excel.Application excelApp = new Excel.Application();
if (excelApp == null)
{
MessageBox.Show("Excel启动失败!");
}
//设置是否显示警告窗体
//excelApp.DisplayAlerts = false;
//设置是否显示Excel
excelApp.Visible = true;
//禁止刷新屏幕
//excelApp.ScreenUpdating = false;
//根据路径path打开
string path = "";
if (checkBox13.Checked)//采用英文模版
{
path = System.AppDomain.CurrentDomain.BaseDirectory + "压力容器工程量清单模板-英文.xlsx";
}
else
{
path = System.AppDomain.CurrentDomain.BaseDirectory + "压力容器工程量清单模板-中文.xlsx";
}
Excel.Workbook xlsWorkBook = excelApp.Workbooks.Open(path, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing,
System.Type.Missing, System.Type.Missing, System.Type.Missing, System.Type.Missing);
//获取Worksheet对象
Excel.Worksheet xlsWorkSheet = (Worksheet)xlsWorkBook.Worksheets["MTO for static equipment"];
//导出datatable
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
xlsWorkSheet.Rows.Cells[i + 4, j + 1] = dt.Rows[i][j].ToString();//excel的第4行开始为数据
}
}
类库
/// <summary>
/// 获取Excel文件数据表列表
/// </summary>
public static ArrayList GetExcelTables(string ExcelFileName)
{
DataTable dt = new DataTable();
ArrayList TablesList = new ArrayList();
if (File.Exists(ExcelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0;Data Source=" + ExcelFileName))
{
try
{
conn.Open();
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
}
catch (Exception exp)
{
throw exp;
}
//获取数据表个数
int tablecount = dt.Rows.Count;
for (int i = 0; i < tablecount; i++)
{
string tablename = dt.Rows[i][2].ToString().Trim().TrimEnd('$');
if (TablesList.IndexOf(tablename) < 0)
{
TablesList.Add(tablename);
}
}
}
}
return TablesList;
}
/// <summary>
/// 将数据导出至Excel文件
/// </summary>
/// <param name="dtData">DataTable对象</param>
/// <param name="FileName">Excel文件路径</param>
public static bool DataTableToExcel(DataTable dt, string fileName)
{
//SaveFileDialog sfd = new SaveFileDialog();
//sfd.Filter = "Excel文件(*.xls)|*.xls|所有文件(*.*)|*.*";
//sfd.Title = "Excel文件导出";
//string fileName = "";
//if (sfd.ShowDialog() == DialogResult.OK)
//{
//fileName = sfd.FileName;
Excel.Application app = new Excel.Application();
if (app == null)
{
MessageBox.Show("Excel启动失败!");
return false;
}
try
{
app.Visible = false;
Excel.Workbook xlWorkBook = app.Workbooks.Add(Type.Missing);
Excel.Worksheet xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
int i;
for (i = 0; i < dt.Columns.Count; i++)
{
xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
}
for (i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string tt = dt.Rows[i][j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = tt;
}
}
xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
xlWorkBook.Close(true, Type.Missing, Type.Missing);
app.Quit();
xlWorkSheet = null;
xlWorkBook = null;
return true;
}
catch (System.Exception exc)
{
MessageBox.Show("excel运行错误:" + exc.Message);
return false;
}
//}
//else
//{
// return false;
//}
}
/// <summary>
/// 将Excel文件导出至DataTable(第一行作为表头)
/// </summary>
/// <param name="ExcelFilePath">Excel文件路径</param>
/// <param name="TableName">数据表名,如果数据表名错误,默认为第一个数据表名</param>
public static DataTable InputFromExcel(string ExcelFilePath, string TableName)
{
if (!File.Exists(ExcelFilePath))
{
throw new Exception("Excel文件不存在!");
}
//如果数据表名不存在,则数据表名为Excel文件的第一个数据表
ArrayList TableList = new ArrayList();
TableList = GetExcelTables(ExcelFilePath);
if (TableName.IndexOf(TableName) < 0)
{
TableName = TableList[0].ToString().Trim();
}
DataTable table = new DataTable();
OleDbConnection dbcon = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0");
OleDbCommand cmd = new OleDbCommand("select * from [" + TableName + "$]", dbcon);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
try
{
if (dbcon.State == ConnectionState.Closed)
{
dbcon.Open();
}
adapter.Fill(table);
}
catch (Exception exp)
{
throw exp;
}
finally
{
if (dbcon.State == ConnectionState.Open)
{
dbcon.Close();
}
}
return table;
}