public class ImportExportToExcel
...{
private string strConn;
public ImportExportToExcel()
...{
//
// TODO: 在此處添加構造函數邏輯
//
}
//從指定的Excel文件導入
public DataSet ImportFromExcel(string strFileName)
...{
DataSet ds = new DataSet();
ds = doImport(strFileName);
return ds;
}
//執行導入
private DataSet doImport(string strFileName)
...{
if(strFileName=="") return null;
strConn = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+strFileName+";Extended PropertIEs=Excel 8.0";
OleDbDataAdapter ExcelDA = new OleDbDataAdapter("select * from [Sheet1$]",this.strConn);//連接字符串
DataSet ExcelDs = new DataSet();//建立數據集,用於存放導入Excel的數據
try
...{
excelDA.Fill(ExcelDs,"ExcelInfo");//填充DataSet
}
catch(Exception ee)
...{
System.Windows.Forms.MessageBox.Show(ee.Message);
}
return ExcelDs;//返回DataSet
}
public void ExportToExcel(DataSet ds,string strExcelFileName)
...{
if(ds.Tables.Count == 0|| strExcelFileName=="") return;
doExport(ds,strExcelFileName);
}
//執行導出
public void doExport(DataSet ds , string strExcelFileName)
...{
Excel.ApplicationClass excel = new Excel.ApplicationClass();//建立Excel對象
int rowIndex = 1;
int colIndex=0;
excel.Application.Workbooks.Add(true);//Excel表為添加狀態
System.Data.DataTable table = ds.Tables[0];//建立DataTable
foreach(DataColumn col in table.Columns)//填充表頭
...{
colIndex++;//列索引值遞增
Excel.Cells[1,colIndex] = col.ColumnName;//指定列填充數據
}
&
nbsp; foreach(DataRow row in table.Rows)//填充數據
...{
rowIndex++;
colIndex=0;
foreach(DataColumn col in table.Columns)
...{
colIndex++;
Excel.Cells[rowIndex,colIndex] = row[col.ColumnName].ToString();
}
}
Excel.Visible = false;
//Excel.Visible = true;
Excel.DisplayAlerts = false;
excel.ActiveWorkbook.SaveAs(strExcelFileName,Excel.XlFileFormat.xlExcel7,Type.Missing,Type.Missing, Type.Missing, Type.Missing,Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Quit();
Excel=null;
GC.Collect();//垃圾回收
}
}