/// <summary>
/// 從Excel文件導入到DataSet
/// </summary>
/// <param name="strFileName"></param>
/// <returns></returns>
public DataSet ImportFromExcel(string strFileName)
{
DataSet ds = new DataSet();
if (strFileName == "")
{
return null;
}
strConn = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFileName + "; Extended Properties=Excel 8.0;";
OleDbDataAdapter dap = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", strConn);
try
{
dap.Fill(ds, "ExcelInfo");
}
catch (Exception err)
{
System.Console.WriteLine(err.ToString());
}
return ds;
}
/// <summary>
/// 從DataSet導出到Excel
/// </summary>
/// <param name="ds"></param>
/// <param name="strExcelFileName"></param>
public void ExportToExcle(DataSet ds, string strExcelFileName)
{
if (ds.Tables.Count == 0 || strExcelFileName == "")
{
return;
}
else
{
Excel.Application excel = new Excel.Application();
int rowIndex = 1;
int colIndex = 0;
excel.Application.Workbooks.Add(true);
DataTable table = ds.Tables[0];
foreach (DataColumn col in table.Columns)
{
colIndex++;
excel.Cells[1, colIndex] = col.ColumnName;
}
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.ActiveWorkbook.SaveAs(strExcelFileName + ".XLS", Excel.XlFileFormat.xlExcel9795, null, null, false, false, Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
excel.Quit();
excel = null;
GC.Collect();
}
}
/// <summary>
/// 從XML導入到DataSet
/// </summary>
/// <param name="strFileName"></param>
/// <returns></returns>
public DataSet ImportFromXML(string strFileName)
{
if (strFileName == "")
{
return null;
}
else
{
DataSet ds = new DataSet();
try
{
ds.ReadXml(strFileName, System.Data.XmlReadMode.Auto);
}
catch
{
}
return ds;
}
}
/// <summary>
/// DataSet導出爲XML
/// </summary>
/// <param name="ds"></param>
/// <param name="strXMLFileName"></param>
public void ExportToXML(DataSet ds, string strXMLFileName)
{
if (ds.Tables.Count == 0 || strXMLFileName == "")
{
return;
}
else
{
try
{
ds.WriteXml(strXMLFileName);
}
catch
{ }
}
}