/// <summary>
/// 导入Excle主控方法
/// </summary>
private void ImportMain()
{
try
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.Filter = "excel filer(*.xls)|*.xls";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//路径名
string pathName = openFileDialog.FileName;
DataTable dtOr = dt_jdsy.Clone();
dt_jdsy = ExcelOperation.ImportExcelToDataTable(pathName);
dtOr.TableName = dt_jdsy.TableName;
DataSet dsOr = new DataSet();
dsOr.Tables.Add(dtOr);
DataSet ds = new DataSet();
ds.Tables.Add(dt_jdsy.Copy());
dt_jdsy = GetDataSet(ds.GetXml(), dsOr.GetXmlSchema()).Tables[0];
gridControl1.DataSource = dt_jdsy;
}
}
catch (Exception ex)
{
throw ex;
}
}
public static System.Data.DataTable ImportExcelToDataTable(string Path)
{
System.Data.DataTable dtSource = new System.Data.DataTable();
try
{
string tableName = "";
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Path + ";" + "Extended Properties=Excel 8.0;";
using (OleDbConnection conn = new OleDbConnection(strConn))
{
Workbook workbook = GetExcelObj(Path);
Worksheet woorksheet = (Worksheet)workbook.ActiveSheet;
tableName = woorksheet.Name;
workbook.Close(false, null, false);
conn.Open();
string strExcel = "";
strExcel = "Select * from [" + tableName + "$]";
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, strConn);
DataSet ds = new DataSet();
myCommand.Fill(ds, tableName);
dtSource = ds.Tables[tableName];
}
}
catch (OleDbException olex)
{
throw new Exception("该Excel文件正在使用中...未能覆盖,请先关闭目标文件,重新导入!");
}
catch (Exception ex)
{
throw ex;
}
finally
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return dtSource;
}