/// <summary>
/// 讀取Excel文檔
/// </summary>
/// <param name=
Path
>文件名稱</param>
/// <returns>返回一個數據集</returns>
public DataSet ExcelToDS(string Path)
{
string strConn =
Provider=Microsoft
Jet
OLEDB
;
+
Data Source=
+ Path +
;
+
Extended Properties=Excel
;
;
OleDbConnection conn = new OleDbConnection(strConn);
conn
Open();
string strExcel =
;
OleDbDataAdapter myCommand = null;
DataSet ds = null;
strExcel=
select * from [sheet
$]
;
myCommand = new OleDbDataAdapter(strExcel
strConn);
ds = new DataSet();
myCommand
Fill(ds
table
);
return ds;
}
/// <summary>
/// 寫入Excel文檔
/// </summary>
/// <param name=
Path
>文件名稱</param>
public bool SaveFP
toExcel(string Path)
{
try
{
string strConn =
Provider=Microsoft
Jet
OLEDB
;
+
Data Source=
+ Path +
;
+
Extended Properties=Excel
;
;
OleDbConnection conn = new OleDbConnection(strConn);
conn
Open();
System
Data
OleDb
OleDbCommand cmd=new OleDbCommand ();
cmd
Connection =conn;
//cmd
CommandText =
UPDATE [sheet
$] SET 姓名=
WHERE 工號=
日期
;
//cmd
ExecuteNonQuery ();
for(int i=
;i<fp
Sheets [
]
RowCount
;i++)
{
if(fp
Sheets [
]
Cells[i
]
Text!=
)
{
cmd
CommandText =
INSERT INTO [sheet
$] (工號
姓名
部門
職務
日期
時間) VALUES(
+fp
Sheets [
]
Cells[i
]
Text+
+
fp
Sheets [
]
Cells[i
]
Text+
+fp
Sheets [
]
Cells[i
]
Text+
+fp
Sheets [
]
Cells[i
]
Text+
+fp
Sheets [
]
Cells[i
]
Text+
+fp
Sheets [
]
Cells[i
]
Text+
)
;
cmd
ExecuteNonQuery ();
}
}
conn
Close ();
return true;
}
catch(System
Data
OleDb
OleDbException ex)
{
System
Diagnostics
Debug
WriteLine (
寫入Excel發生錯誤
+ex
Message );
}
return false;
}
From:http://tw.wingwit.com/Article/program/net/201311/13097.html