合并两个或多个excel文件

时间:2017-04-04 04:57:57

标签: c# excel

我被困在合并两个或更多excel单元格中。如果标题从合并开始[0,0]成功发生。如果标题不是从[0,0]开始,则合并失败。 我正在使用导入的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;
        }


    }

1 个答案:

答案 0 :(得分: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);
相关问题