如果想要存取Microsoft Office的軟體,需先裝Database Engine才可以讓自己寫的程式跟Office軟體做溝通,不管是Excel或Access等都好,安裝完成後,在Visual Studio加入兩個參考:
1. LinqToExcel 這個.dll檔需要另外在NuGet套件安裝,目前只提供快速查詢Excel資料的功能,沒有將資料寫入Excel的功能,所以用Microsoft.Office.Interop.Excel來實現寫入的功能.
2. Microsoft.Office.Interop.Excel
using LinqToExcel.Attributes;
class Guest
{
//將Excel欄位名稱與程式變數連結
//the name of column in excel file, 引號內的名稱是Excel檔案的欄位名稱
[ExcelColumn("時間戳記")]
public string Time { get; set; }
[ExcelColumn("姓名 : ")]
public string Name { get; set; }
[ExcelColumn("職稱 : ")]
public string Jobtitle { get; set; }
[ExcelColumn("學校 : ")]
public string School { get; set; }
[ExcelColumn("科系 : ")]
public string Depart { get; set; }
[ExcelColumn("手機 :")]
public string Phone { get; set; }
[ExcelColumn("E-mail : ")]
public string Email { get; set; }
[ExcelColumn("餐點 : ")]
public string Meal { get; set; }
[ExcelColumn("卡號")]
public string CardNum { get; set; }
}
//讀取Excel資料
string pathToExcelFile = @"G:\e_register\e_register\SIGRegistration.xlsx"; //s
string sheetName = "sheet1"; //Excel檔案內的sheet名稱
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var artistAlbums = from a in excelFile.Worksheet(sheetName) where a.CardNum == tb_cardnum.Text select a;
foreach (var a in artistAlbums)
{
tb_name.Text = a.Name; //tb_name為TextBox元件名稱,以下一樣
tb_cellphone.Text = a.Phone;
tb_depart.Text = a.Depart;
tb_school.Text = a.School;
tb_jobtitle.Text = a.Jobtitle;
tb_email.Text = a.Email;
}
//將資料寫入Excel
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='G:\e_register\e_register\SIGRegistration.xlsx';Extended Properties=Excel 12.0";
using (OleDbConnection oledbConn = new OleDbConnection(ConnectionString))
{
oledbConn.Open();
string sql = "Update [sheet1$] set 時間戳記 = @p1 where 卡號=@p2";
using (OleDbCommand cmd = new OleDbCommand(sql, oledbConn))
{
cmd.Parameters.AddWithValue("@p1", DateTime.Now.ToString());
cmd.Parameters.AddWithValue("@p2", tb_cardnum.Text);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
附件有結合RFID僅供參考程式碼