private bool ImportDaysFromExcel() { //return false; bool output = false; int NewCustomerFounded = 0; int NewRouteFounded = 0; int NewProductFounded = 0; AddLog("Start importing ..."); DataTable dtExcel = new DataTable(); SplashScreenManager.ShowForm(typeof(WaitWindowFrm)); this.Invoke(new MethodInvoker(() => { for (int i = 0; i < lbcFilePath.ItemCount; i++) { if (File.Exists(lbcFilePath.Items[i].ToString())) { SplashScreenManager.Default.SetWaitFormDescription("Loading Excel File [" + (i + 1) + "] Contains [1/4]"); DataTable dtPart = DataManager.LoadExcelFile(lbcFilePath.Items[i].ToString(), 0, "*"); if (dtPart.Rows.Count == 0) continue; dtExcel.Merge(dtPart); } } SplashScreenManager.Default.SetWaitFormDescription("Loading Customers Informations [2/4]"); _0_6_Customer_HNTableAdapter.Fill(dsData._0_6_Customer_HN); SplashScreenManager.Default.SetWaitFormDescription("Loading Routes Informations [3/4]"); _0_3__Route_DetailsTableAdapter.Fill(dsData._0_3__Route_Details); SplashScreenManager.Default.SetWaitFormDescription("Loading Products Informations [4/4]"); _0_4__Product_DetailsTableAdapter.Fill(dsData._0_4__Product_Details); })); if (dtExcel.Rows.Count == 0) return false; DateTime dtStart = DateTime.Now; OleDbConnection con = new OleDbConnection(Properties.Settings.Default.dbConnectionString); OleDbCommand cmd = new OleDbCommand("", con); Microsoft.Office.Interop.Access.Dao.DBEngine eng = new Microsoft.Office.Interop.Access.Dao.DBEngine(); Microsoft.Office.Interop.Access.Dao.Database db = eng.OpenDatabase(DataManager.dbPath); eng.BeginTrans(); Microsoft.Office.Interop.Access.Dao.Recordset rs = db.OpenRecordset(@"SELECT [Billing Document], [Billing date for bil], [Billing Type], [Payer], [Sold-to party], [Actual Invoiced Quan], [Condition base value], [Condition type], [Condition value], [Distribution Channel], [G/L Account Number], [Material Number], [Plant], [Reference Document N], [Route], [Sales district], [Sales unit], [Company Code], [Base Unit of Measure], [Sales Organization], [Route & Sold], [yeard], [Month], [New Quanteite] FROM [0-1 Master]"); Microsoft.Office.Interop.Access.Dao.Field[] myFields = new Microsoft.Office.Interop.Access.Dao.Field[25]; for (int k = 0; k <= 23; k++) { myFields[k] = rs.Fields[k]; } con.Open(); int ProcessedCounter = 0; int ProcessedMax = dtExcel.Rows.Count; this.Invoke(new MethodInvoker(() => { ProgressBarMain.Properties.Maximum = ProcessedMax; ProgressBarMain.EditValue = ProcessedCounter; })); //deleting data before saving new 1 var result = from row in dtExcel.AsEnumerable() group row by row["Billing date for bil"] into grp select new { BillingDate = grp.Key }; cmd.CommandText = "delete from [0-1 Master] where [Billing date for bil] = @BillingDate"; cmd.Parameters.Add(new OleDbParameter("@BillingDate", OleDbType.Date)); foreach (var item in result) { if (DevExpress.XtraSplashScreen.SplashScreenManager.Default.IsSplashFormVisible) DevExpress.XtraSplashScreen.SplashScreenManager.Default.SetWaitFormDescription("Deleting Day " + item.BillingDate); System.Windows.Forms.Application.DoEvents(); cmd.Parameters["@BillingDate"].Value = item.BillingDate; cmd.ExecuteNonQuery(); } SplashScreenManager.CloseForm(); int Test = 0; foreach (DataRow row in dtExcel.Rows) { //Update UI ProcessedCounter++; if (ProcessedCounter % 500 == 1) { //double DonePercent = ProcessedCounter / ProcessedMax; this.Invoke(new MethodInvoker(() => { lblEstTime.Text = Convert.ToInt32(DateTime.Now.Subtract(dtStart).TotalSeconds / ProcessedCounter * ProcessedMax) + " sec"; ProgressBarMain.EditValue = ProcessedCounter; lblCount.Text = string.Format("{0}/{1}", ProcessedMax, ProcessedCounter); Application.DoEvents(); })); } //if (Test == 21501) //{ // string x = ""; //} Test++; Data.dsData._0_1__MasterRow SqlRow = dsData._0_1__Master.New_0_1__MasterRow(); SqlRow.Billing_Document = row["Billing Document"].ToString(); SqlRow.Billing_date_for_bil = Convert.ToDateTime(row["Billing date for bil"]); SqlRow.yeard = SqlRow.Billing_date_for_bil.Year.ToString(); SqlRow.Month = SqlRow.Billing_date_for_bil.ToString("MMMM", System.Globalization.CultureInfo.InvariantCulture); SqlRow.Billing_Type = row["Billing Type"].ToString(); //SqlRow.Payer = row["Payer"].ToString(); SqlRow._Sold_to_party = Convert.ToInt32(row["Sold-to party"]).ToString(); SqlRow.Actual_Invoiced_Quan = Convert.ToDouble(row["Actual Invoiced Quan"]); //SqlRow.Condition_base_value = Convert.ToDouble(row["Condition base value"]); SqlRow.Condition_type = row["Condition type"].ToString(); SqlRow.Condition_value = Convert.ToDouble(row["Condition value"]); SqlRow.Distribution_Channel = row["Distribution Channel"].ToString(); //SqlRow._G_L_Account_Number = row["G/L Account Number"].ToString(); SqlRow.Material_Number = Convert.ToInt32(row["Material Number"]); SqlRow.Plant = row["Plant"].ToString(); SqlRow.Reference_Document_N = row["Reference Document N"].ToString(); //Set Route and Fix 999999 and 000001 SqlRow.Route = row["Route"].ToString(); if (SqlRow.Route == DataManager.Route999999) { if (SqlRow.Reference_Document_N.Trim().Substring(0, 2) == "CS")//try to get it from "Reference Document N" SqlRow.Route = SqlRow.Reference_Document_N.Trim().Substring(2, 6); else { //try to get it from last route for this "Sold to-party" cmd.CommandText = string.Format("SELECT top 1 Route FROM [0-1 Master] WHERE [Sold-to party] = \"{0}\" AND [0-1 Master].Route <> \"999999\" order by [Billing date for bil] DESC", SqlRow._Sold_to_party); object obj = cmd.ExecuteScalar(); if (obj != null) SqlRow.Route = obj.ToString(); } } //Set _Route___Sold if (SqlRow.Route == DataManager.Route000001) SqlRow._Route___Sold = SqlRow._Sold_to_party; else SqlRow._Route___Sold = SqlRow.Route; //SqlRow.Sales_district = row["Sales district"].ToString(); SqlRow.Sales_unit = row["Sales unit"].ToString(); //SqlRow.Company_Code = row["Company Code"].ToString(); //SqlRow.Base_Unit_of_Measure = row["Base Unit of Measure"].ToString(); //SqlRow.Sales_Organization = row["Sales Organization"].ToString(); //Customer Update Data.dsData._0_6_Customer_HNRow CustomerRow = Customer.GetCustomerRow(SqlRow._Sold_to_party, dsData._0_6_Customer_HN); if (CustomerRow.RowState == DataRowState.Detached) { CustomerRow.Customer_T = SqlRow._Sold_to_party; CustomerRow.Customer_Type = Customer.CustomerTypeIdDirect; CustomerRow.Customer_Type_2 = Customer.CustomerType2IdDirect; CustomerRow.Customer_Group = Customer.CustomerGroupIdDirect; CustomerRow.Subchannel = Customer.SubchannelIdDirect; CustomerRow.Customer_type_Code = Customer.CustomerTypeCodeDirect; dsData._0_6_Customer_HN.Add_0_6_Customer_HNRow(CustomerRow); CustomerRow.EndEdit(); AddLog("[New Customer Found] : " + row["Sold-to party"]); NewCustomerFounded++; } //Route Update if (row["Route"].ToString().Trim() != DataManager.Route000001 && row["Route"].ToString().Trim() != DataManager.Route999999) { Data.dsData._0_3__Route_DetailsRow RouteRow = Route.GetRouteNumber(row["Route"].ToString().Trim(), dsData._0_3__Route_Details); if (RouteRow.RowState == DataRowState.Detached) { RouteRow.Route_Number = SqlRow.Route; dsData._0_3__Route_Details.Add_0_3__Route_DetailsRow(RouteRow); RouteRow.EndEdit(); AddLog("[New Route Found] : " + RouteRow.Route_Number); NewRouteFounded++; } } //Product Update Data.dsData._0_4__Product_DetailsRow ProductRow = Product.GetProductRow(SqlRow.Material_Number, dsData._0_4__Product_Details); if (ProductRow.RowState == DataRowState.Detached) { ProductRow.Material_Number = SqlRow.Material_Number; dsData._0_4__Product_Details.Add_0_4__Product_DetailsRow(ProductRow); ProductRow.EndEdit(); AddLog("[New Product Found] : " + ProductRow.Material_Number); NewProductFounded++; } if (ProductRow.Quin == ProductRow.New_Qu) SqlRow.New_Quanteite = Convert.ToInt32(SqlRow.Actual_Invoiced_Quan); else SqlRow.New_Quanteite = Convert.ToInt32(SqlRow.Actual_Invoiced_Quan * ProductRow.Quin / ProductRow.New_Qu); dsData._0_1__Master.Add_0_1__MasterRow(SqlRow); SqlRow.EndEdit(); //_0_1__MasterTableAdapter.Update(SqlRow); rs.AddNew(); myFields[0].Value = SqlRow.Billing_Document; myFields[1].Value = SqlRow.Billing_date_for_bil; myFields[2].Value = SqlRow.Billing_Type; //myFields[3].Value = SqlRow.Payer; myFields[4].Value = SqlRow._Sold_to_party; myFields[5].Value = SqlRow.Actual_Invoiced_Quan; //myFields[6].Value = SqlRow.Condition_base_value; myFields[7].Value = SqlRow.Condition_type; myFields[8].Value = SqlRow.Condition_value; myFields[9].Value = SqlRow.Distribution_Channel; //myFields[10].Value = SqlRow._G_L_Account_Number; myFields[11].Value = SqlRow.Material_Number; myFields[12].Value = SqlRow.Plant; myFields[13].Value = SqlRow.Reference_Document_N; myFields[14].Value = SqlRow.Route; //myFields[15].Value = SqlRow.Sales_district; myFields[16].Value = SqlRow.Sales_unit; //myFields[17].Value = SqlRow.Company_Code; //myFields[18].Value = SqlRow.Base_Unit_of_Measure; //myFields[19].Value = SqlRow.Sales_Organization; myFields[20].Value = SqlRow._Route___Sold; myFields[21].Value = SqlRow.yeard; myFields[22].Value = SqlRow.Month; myFields[23].Value = SqlRow.New_Quanteite; rs.Update(); } eng.CommitTrans(); eng.FreeLocks(); db.Close(); _0_6_Customer_HNTableAdapter.Update(dsData._0_6_Customer_HN); _0_3__Route_DetailsTableAdapter.Update(dsData._0_3__Route_Details); _0_4__Product_DetailsTableAdapter.Update(dsData._0_4__Product_Details); ////SplashScreenManager.ShowForm(typeof(WaitWindowFrm)); ////SplashScreenManager.Default.SetWaitFormDescription("Updating Master ..."); Application.DoEvents(); ////int index = 0; ////foreach (Data.dsData._0_1__MasterRow row in dsData._0_1__Master) ////{ //// _0_1__MasterTableAdapter.Update(row); //// SplashScreenManager.Default.SetWaitFormDescription("Updating Master ..." + index); index++; //// Application.DoEvents(); ////} //_0_1__MasterTableAdapter.Update(dsData._0_1__Master); dsData._0_1__Master.AcceptChanges(); AddLog("New Customers Saved " + NewCustomerFounded); AddLog("New Routes Saved " + NewRouteFounded); AddLog("New Product Saved " + NewProductFounded); AddLog("New R3 Data Saved " + dsData._0_1__Master.Count); dtExcel.Rows.Clear(); dtExcel.Dispose(); dtExcel = null; dsData._0_1__Master.Clear(); dsData._0_6_Customer_HN.Clear(); dsData._0_1__Master.Dispose(); dsData._0_6_Customer_HN.Dispose(); cmd.Dispose(); cmd = null; con.Close(); con.Dispose(); con = null; GC.Collect(); GC.WaitForPendingFinalizers(); return output; }
static void Main(string[] args) { // required COM reference: Microsoft Office 14.0 Access Database Engine Object Library var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine(); Microsoft.Office.Interop.Access.Dao.Database db = dbe.Workspaces[0].OpenDatabase(@"C:\Users\Public\Database1.accdb"); Microsoft.Office.Interop.Access.Dao.Field fld = db.TableDefs["myTable"].Fields["oldFieldName"]; fld.Name = "newFieldName"; db.Close(); }
static void Main(string[] args) { // required COM reference: Microsoft Office 14.0 Access Database Engine Object Library var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine(); Microsoft.Office.Interop.Access.Dao.Database db = dbe.Workspaces[0].OpenDatabase(@"C:\__tmp\testData.accdb"); Microsoft.Office.Interop.Access.Dao.Field fld = db.TableDefs["poiData"].Fields["lon"]; Console.WriteLine("Properties[\"DecimalPlaces\"].Value was: " + fld.Properties["DecimalPlaces"].Value); fld.Properties["DecimalPlaces"].Value = 5; Console.WriteLine("Properties[\"DecimalPlaces\"].Value is now: " + fld.Properties["DecimalPlaces"].Value); db.Close(); Console.WriteLine("Hit a key..."); Console.ReadKey(); }
private void linkTable(string fromTable, string toTable) { Microsoft.Office.Interop.Access.Dao.DBEngine dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine(); Microsoft.Office.Interop.Access.Dao.Database db; Microsoft.Office.Interop.Access.Dao.Workspace wrk; wrk = dbe.CreateWorkspace("", "admin", "", Microsoft.Office.Interop.Access.Dao.WorkspaceTypeEnum.dbUseJet); db = wrk.OpenDatabase(textBoxPathAccess.Text); Microsoft.Office.Interop.Access.Dao.TableDef tdf = db.CreateTableDef(); // MySQL ODBC 5.3 ANSI Driver tdf.Connect = "ODBC;Driver={" + OdbcDriver + "};Server=" + textBoxMysqlServer.Text + ";Port=" + textBoxMysqlPort.Text + ";Database=" + DatabaseName() + ";User="******";Password="******";Option=3;"; tdf.Connect = "ODBC;DSN=myDatabase"; tdf.SourceTableName = fromTable; tdf.Name = toTable; db.TableDefs.Append(tdf); }
static void Main(string[] args) { string TableName = "Cars"; string FieldName = "CarType"; // This code requires the following COM reference in your project: // // Microsoft Office 14.0 Access Database Engine Object Library // var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine(); Microsoft.Office.Interop.Access.Dao.Database db = dbe.OpenDatabase(@"Z:\_xfer\Database1.accdb"); try { Microsoft.Office.Interop.Access.Dao.Field fld = db.TableDefs[TableName].Fields[FieldName]; string RowSource = ""; try { RowSource = fld.Properties["RowSource"].Value; } catch { // do nothing - RowSource will remain an empty string } if (RowSource.Length == 0) { Console.WriteLine("The field is not a lookup field."); } else { Console.WriteLine(RowSource); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
public string RepairAccess(string mdbPath) { string strResult = ""; //声明临时数据库的名称 string temp = DateTime.Now.Year.ToString(); temp += DateTime.Now.Month.ToString(); temp += DateTime.Now.Day.ToString(); temp += DateTime.Now.Hour.ToString(); temp += DateTime.Now.Minute.ToString(); temp += DateTime.Now.Second.ToString() + ".accdb"; temp = mdbPath.Substring(0, mdbPath.LastIndexOf("\\") + 1) + temp; string strlock = mdbPath.Substring(0, mdbPath.LastIndexOf("\\") + 1) + "TransferLock"; string sourceDbSpec = mdbPath; string destinationDbSpec = temp; // Required COM reference for project: // Microsoft Office 14.0 Access Database Engine Object Library var dbe = new Microsoft.Office.Interop.Access.Dao.DBEngine(); try { File.Create(strlock).Dispose(); File.WriteAllText(strlock, GetComputerName()); dbe.CompactDatabase(sourceDbSpec, destinationDbSpec); File.Delete(mdbPath); File.Copy(destinationDbSpec, mdbPath, true); strResult = "修复成功!"; } catch (Exception e) { strResult = "Error: " + e.Message; } File.Delete(strlock); return(strResult); }
/* * public Boolean dbOpen(string strFilePath) * { * m_Provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; * try * { * System.IO.FileInfo dbFile = new System.IO.FileInfo(strFilePath); * if (!dbFile.Exists) m_dbOpen = false; * else * { * m_ObjCon.Open(); * m_dbOpen = true; * } * } * catch (Exception e) * { * m_dbOpen = false; * e.ToString(); * } * return m_dbOpen; * } */ public Boolean dbOpen(string strFilePath) { Boolean bCreate = false; m_Provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; try { System.IO.FileInfo dbFile = new System.IO.FileInfo(strFilePath); if (!dbFile.Exists) { //// DB 파일이름으로 .accdb 만들기. Catalog myCatalog = new Catalog(); //string strProvider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; //string strProvider = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; try { myCatalog.Create(m_Provider); bCreate = true; } catch (Exception ex) { //MessageBox.Show(ex.Message, "Make AccessDB Error"); Console.WriteLine(ex.Message); return(false); } } else { //로컬 DB 데이터 압축. 데이터 압축 해주지 않으면 로컬 DB 파일의 사이즈가 계속 커지게 된다. //Table 을 삭제해도 로컬 DB 내에 복구를 위한 데이터는 남아있다. 데이터 압축을 해주면 복구용 데이터를 모두 삭제한다. try { //임시파일 string strTempFilePath = "C:/temp.accdb"; if (System.IO.File.Exists(strTempFilePath)) { System.IO.File.Delete(strTempFilePath); } //MDB 파일 데이터 압축. JRO 라이브러리 로드가 필요하다. //JRO.JetEngine ddd = new JRO.JetEngine(); //string temp1 = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; //string temp2 = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + strTempFilePath + ";Jet OLEDB:Database Password ="******"; "; //ddd.CompactDatabase(temp1, temp2); //accdb 파일 데이터 압축 Microsoft.Office.Interop.Access.Dao.DBEngine objDbEngine = new Microsoft.Office.Interop.Access.Dao.DBEngine(); objDbEngine.CompactDatabase(strFilePath, strTempFilePath, null, null, ";pwd=" + m_DBPassword);//데이터 압축 if (System.IO.File.Exists(strTempFilePath)) { System.IO.File.Delete(strFilePath); System.IO.File.Move(strTempFilePath, strFilePath); } } catch (Exception e) { Console.WriteLine(e.Message); } } ; //mdb 파일 //m_ObjCon.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";Jet OLEDB:Database Password ="******"; "; //accdb 파일 //m_ObjCon.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ strFilePath+ ";Jet OLEDB:Database Password ="******";"; //+ "Persist Security Info=False;" //+ "Database Password=gtf_stfm;"; m_ObjCon.Open(); m_dbOpen = true; if (bCreate) { if (!createBasicTable()) { m_ObjCon.Close(); m_ObjCon = null; if (System.IO.File.Exists(strFilePath)) { System.IO.File.Delete(strFilePath); } return(false); } } else { // table data 삭제 DeleteTableData("REFUNDSLIP"); DeleteTableData("SALES_GOODS"); DeleteTableData("SLIP_PRINT_DOCS"); DeleteTableData("REFUND_SLIP_SIGN"); } } catch (Exception e) { m_dbOpen = false; e.ToString(); } return(m_dbOpen); }
static void Main(string[] args) { const string fieldname_filename = "FileName"; const string fieldname_filedata = "FileData"; string outputfolder = @"D:\attachments"; string dbfilename = @"D:\\AX6Reports.accdb"; string tablename = "AX6Reports"; var prefix_fieldnames = new[] { "Name", "Design" }; string attachment_fieldname = "Attachments"; var dbe = new MSACCESS.Dao.DBEngine(); var db = dbe.OpenDatabase(dbfilename, false, false, ""); var rstype = MSACCESS.Dao.RecordsetTypeEnum.dbOpenDynaset; var locktype = MSACCESS.Dao.LockTypeEnum.dbOptimistic; string selectclause = string.Format("SELECT * FROM {0}", tablename); var rs = db.OpenRecordset(selectclause, rstype, 0, locktype); rs.MoveFirst(); int row_count = 0; while (!rs.EOF) { var prefix_values = prefix_fieldnames.Select(s => rs.Fields[s].Value).ToArray(); var attachment_rs = (MSACCESS.Dao.Recordset2)rs.Fields[attachment_fieldname].Value; int attachment_count = 0; while (!attachment_rs.EOF) { var field_filename = attachment_rs.Fields[fieldname_filename].Value; var field_attachment = (MSACCESS.Dao.Field2)attachment_rs.Fields[fieldname_filedata]; if (field_attachment != null) { if (field_attachment.Value != null) { string prefix = ""; if (prefix_fieldnames.Length > 0) { prefix = string.Format("{0}__", string.Join("__", prefix_values)); prefix = prefix.Replace(" ", "_"); prefix = prefix.Replace(":", "_"); prefix = prefix.Replace("/", "_"); } var dest_fname = System.IO.Path.Combine(outputfolder, prefix + field_filename); if (System.IO.File.Exists(dest_fname)) { System.IO.File.Delete(dest_fname); } field_attachment.SaveToFile(dest_fname); } } attachment_rs.MoveNext(); attachment_count++; } attachment_rs.Close(); Console.WriteLine(row_count); row_count++; rs.MoveNext(); } rs.Close(); }
private void buttonCompactDatabase_Click(object sender, EventArgs e) { // // 参考 // Microsoft Access Compact and Repair using C# .accdb files - Stack Overflow // http://stackoverflow.com/questions/29201611/microsoft-access-compact-and-repair-using-c-sharp-accdb-files // // "プロジェクト"→"参照の追加"で参照マネージャーを表示 // 次に"COM"→"Microsoft Office 14.0 Access Database Engine Object Library"を選択し // 参照を追加するとMicrosoft.Office.Interop.Access.Dao.DBEngineを使えるようになる // var dbengine = new Microsoft.Office.Interop.Access.Dao.DBEngine(); var src = AccdbFilePath(); var dst = NewAccdbFilePath(); var bak = BackupAccdbFilePath(); if (File.Exists(dst)) { File.Delete(dst); } dbengine.CompactDatabase(src, dst); if (File.Exists(bak)) { File.Delete(bak); } File.Move(src, bak); File.Move(dst, src); Console.WriteLine("buttonCompactDatabase_Click"); }