C#控制台从文件夹导入Excel到SQL
我有这个代码,它工作正常。
public partial class CS { static void LoadExcelMain(string excelPath) { string conString = string.Empty; string extension = Path.GetExtension(excelPath); switch (extension) { case ".xls": conString = @PH_MM_ExcelDataReader.Properties.Settings.Default.Excel03ConString; break; case ".xlsx": conString = @PH_MM_ExcelDataReader.Properties.Settings.Default.Excel07ConString; break; } conString = string.Format(conString, excelPath); using (OleDbConnection excel_con = new OleDbConnection(conString)) { excel_con.Open(); string sheet1 = excel_con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null).Rows[0]["TABLE_NAME"].ToString(); DataTable dtExcelData = new DataTable(); dtExcelData.Columns.AddRange(new DataColumn[16] { new DataColumn("MMRequestNo", typeof(string)), new DataColumn("MaterialNumber", typeof(string)), new DataColumn("ProductionVersion",typeof(string)) }); using (OleDbDataAdapter oda = new OleDbDataAdapter("SELECT * FROM [" + sheet1 + "]", excel_con)) { oda.Fill(dtExcelData); } excel_con.Close(); string consString = @PH_MM_ExcelDataReader.Properties.Settings.Default.ConnString; using (SqlConnection con = new SqlConnection(consString)) { using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con)) { sqlBulkCopy.DestinationTableName = @PH_MM_ExcelDataReader.Properties.Settings.Default.DBTable; sqlBulkCopy.ColumnMappings.Add("MMRequestNo", "MMRequestNo"); sqlBulkCopy.ColumnMappings.Add("MaterialNumber", "MaterialNumber"); sqlBulkCopy.ColumnMappings.Add("ProductionVersion", "ProdVersion"); con.Open(); sqlBulkCopy.WriteToServer(dtExcelData); con.Close(); File.Delete(@PH_MM_ExcelDataReader.Properties.Settings.Default.FileLocationPath + "\\Product_Costing_Template.xlsx"); } } } } static void Main(string[] args) { LoadExcelMain(PH_MM_ExcelDataReader.Properties.Settings.Default.FileLocationPath + "\\Product_Costing_Template.xlsx"); } }
我也有两张桌子; 一个是excel文件的内容,另一个是文件的细节。
tableName: FileDetails --------------------------------- |FileName|RequestDate|isDone|Logs| |--------|-----------|------|----|
我想要做的是根据RequestDate与这个程序进行处理,我目前只有文件名开头的“PH”的excel文件