2017-04-04 235 views
0

我被困在合併兩個或多個Excel單元格。如果頭文件從合併開始[0,0]成功發生。如果標題沒有從[0,0]開始,則合併失敗。 我正在檢查標準excel列名與導入的Excel表單列名稱。合併兩個或多個Excel文件

public DataTable GetDataTable(string filepath) 
    { 
     var prevCulture = Thread.CurrentThread.CurrentCulture; 
     Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; 
     OleDbConnection conn = null; 
     DataTable dtSourceData = new DataTable(); 
     string excelpath = filepath; 
     #region connection 
     if(excelpath!="") 
     { 
      try 
      { 
       OleDbConnectionStringBuilder sbConnection = new OleDbConnectionStringBuilder(); 
       String strExtendedProperties = String.Empty; 
       sbConnection.DataSource = excelpath; 
       sbConnection.Provider = "Microsoft.ACE.OLEDB.12.0"; 
       strExtendedProperties = "Excel 12.0;HDR=Yes;IMEX=1"; 
       sbConnection.Add("Extended Properties", strExtendedProperties); 

       conn = new OleDbConnection(sbConnection.ToString()); 
       conn.Open(); 
      } 
      catch 
      { 
       try 
       { 
        conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.14.0;" + 
         "Data Source=" + excelpath + 
         ";Extended Properties=Excel 14.0 Xml"); 
        conn.Open(); 
       } 
       catch 
       { 
        try 
        { 
         conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.15.0;" + 
          "Data Source=" + excelpath + 
          ";Extended Properties=Excel 15.0 Xml"); 
         conn.Open(); 
        } 
        catch 
        { 
         try 
         { 
          conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" + 
               "Data Source=" + excelpath + 
               ";Extended Properties=''"); 
          conn.Open(); 
         } 
         catch (FileNotFoundException ex) 
         { 
          MessageBox.Show(ex.Message); 
          //throw ex; 
         } 
        } 
       } 
      } 
     } 
     else 
     { 
      MessageBox.Show("Standard Template file is not found"); 
     } 

     #endregion 

     try 
     { 

      List<string> sheetName = new List<string>(); 
      sheetName = ListSheetInExcel(excelpath); 
      for(int sheet=0;sheet<sheetName.Count;sheet++) 
      { 
       string tmpsheetName = sheetName[sheet]; 
       tmpsheetName = tmpsheetName.TrimEnd('$'); 
       tmpsheetName = tmpsheetName.TrimEnd('\''); 
       tmpsheetName = tmpsheetName.TrimEnd('$'); 
       tmpsheetName = tmpsheetName.TrimStart('\''); 

       string CreateCommand = "SELECT * FROM [" + tmpsheetName + "$]"; 
       var MyCommand = new System.Data.OleDb.OleDbDataAdapter(CreateCommand, conn); 
       MyCommand.FillSchema(dtSourceData, SchemaType.Source); 
       MyCommand.Fill(dtSourceData); 
       MyCommand.Dispose(); 
       conn.Close(); 
      } 
      return dtSourceData; 

     } 
     catch(Exception er) 
     { 
      MessageBox.Show("GetDataTable"+er.Message); 
      throw er; 
     } 
     finally 
     { 
      Thread.CurrentThread.CurrentCulture = prevCulture; 
     } 
    } 

    int cnt = 0; 

    public DataTable MapDataTables(DataTable PrevDataTable, DataTable CurrDataTable, IEnumerable<XElement> ColumnNodes) 
    { 
     DataTable result = PrevDataTable; 
     bool isFirstTime = true; 
     int i = 0, prevRowCount = result.Rows.Count, totRowCount = result.Rows.Count + CurrDataTable.Rows.Count; 
     int j = 0; 
     int preRowCnt = PrevDataTable.Rows.Count; 
     bool isKeyFound = false; 
     j = CurrDataTable.Rows.Count; 
     try 
     { 
      foreach (XElement col in ColumnNodes) 
      { 
       string newColName = col.Attribute("Name").Value; 

        foreach (XElement colname in col.Elements()) 
        { 
         isKeyFound = false; 
         foreach (DataColumn dc in CurrDataTable.Columns) 
         {        
           if (colname.Value == dc.ColumnName.Replace(".", "").Replace(" ", "").Replace("(", "").Replace(")", "").Replace("&", "").Replace("/", ""))                
           { 
            int rowCnt = PrevDataTable.Rows.Count; 
            for (i = 0; i < CurrDataTable.Rows.Count; i++) 
            { 
             // if (CurrDataTable.Rows.Count < result.Rows.Count) 
             // { 
             if (isFirstTime) 
             { 
              DataRow toInsert = result.NewRow(); 
              result.Rows.InsertAt(toInsert, i); 
              result.Rows[i][newColName] = CurrDataTable.Rows[i][dc.ColumnName]; 
              cnt++; 
             } 
             else 
             { 
              result.Rows[i][newColName] = CurrDataTable.Rows[i][dc.ColumnName]; 
              j++; 
             }           
            } 
            isFirstTime = false; 
           } 
         } 
        } 
        if (isKeyFound) 
        { 
         break; 
        } 

       }     
       return result; 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("MapDataTables" + ex.Message); 
       return null; 
      } 
     } 


    private void btnUpdate_Click(object sender, EventArgs e) 
    { 
     try 
     {       
      string stdTemplateFile = ProjPath + "\\Standard Format.xls"; 
      string inputpath = ""; //= txtPath.Text; 
      XDocument doc = new XDocument(); 
      doc = XDocument.Load(@"Settings.xml"); 

      var elem = doc.Element("Settings").Element("FieldName").Elements();    

      if (File.Exists(stdTemplateFile)) 
      { 

       var MapedTable = (dynamic)null; 
       if (ChkListBox.CheckedItems.Count > 0) 
       { 
        string tempPath = Path.Combine(Path.GetDirectoryName(stdTemplateFile), Path.GetFileNameWithoutExtension(stdTemplateFile) + "_copy.xls"); 

        foreach (string CheckedFile in ChkListBox.CheckedItems) 
        { 
         inputpath = CheckedFile;       
         var PrevDataTable = GetDataTable(tempPath);            
         var tmpData = PrevDataTable; 
         var CurDataTable = GetDataTable(inputpath);        
         MapedTable = MapDataTables(PrevDataTable, CurDataTable, elem);        
         writeToExcel(CurDataTable, PrevDataTable, tempPath);       
        }     

        MessageBox.Show("Completed"); 
        ChkListBox.Items.Clear(); 
       } 
      } 
     } 
     catch(Exception er) 
     { 
      MessageBox.Show("Update_Click" + er.Message); 
      //throw er; 
     } 


    } 
+0

利用好圖書館。像kim說... – tgkprog

回答

1

我會推薦使用EPPLUS。在這裏我不會給你一個例子,但是你提供的關於打開文件的很多代碼很容易在EPPLUS內完成。

示例代碼:

ExcelPackage package = new ExcelPackage(/*FileInfo object*/); 
ExcelWorksheet sheet = package.Workbook.Worksheets.FirstOrDefault(); 
var cellValues= ((object[,])sheet.Cells[0, 1, 0, 20].Value);