从多个Excel文档中读取数据并将其写入另一个Excel文档中

2024-01-29

目前,我只能读取一个 Excel 文档,并用我得到的代码编写相同的文档。现在我想从多个Excel文档中读取数据并将数据写入一个文档中。现在我在一个文档中得到了执行此操作的清晰代码,但这不是我想要的。我了解目前得到的代码的结构,所以我更喜欢保留它。我将如何做到这一点excel_init函数和与excel_getValue功能?

这是我到目前为止所拥有的:

static void Main(string[] args)
        {
            excel_init("C:\\Users\\Admin\\Desktop\\excel1.xlsx");
            List<string> list = new List<string>();

            for (int i = 1; i <= 10; i++)
            {
                string firstColomExcelFile1 = "A" + i;
                string allExcelDataFile1 = excel_getValue(firstColomExcelFile1);

                excel_setValue("B" + i, allExcelDataFile1); //this has to happen in a different excel doc, on sheet 2

                list.Add(allExcelDataFile1);
                Console.WriteLine(allExcelDataFile1);
            }

            excel_close();
            excel_init("C:\\Users\\Admin\\Desktop\\excel1.xlsx");
            for (int j = 1; j < 5; j++) // loop for other excel document
            {
                string firstColomExcelFile2 = "A" + i;
                string allExcelDataFile2 = excel_getValue(firstColomExcelFile2);

                excel_setValue("C" + i, allExcelDataFile2);
                Console.WriteLine(allExcelDataFile2);
            } 
            excel_close();

           // here I want to paste my lists in another doc file. 

            Console.WriteLine("Press key to continue");
            Console.ReadKey();
        }

        private static Microsoft.Office.Interop.Excel.ApplicationClass appExcel;
        private static Workbook newWorkbook = null;
        private static _Worksheet objsheet = null;

        //Method to initialize opening Excel
        static void excel_init(String path)
        {
            appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();

            if (System.IO.File.Exists(path))
            {
                // then go and load this into excel
                newWorkbook = appExcel.Workbooks.Open(path, true, true);
                objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
            }
            else
            {
                Console.WriteLine("Unable to open file!");
                System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
                appExcel = null;
            }

        }
        static void excel_setValue(string cellname, string value)
        {
            objsheet.get_Range(cellname).set_Value(Type.Missing, value);
        }

        //Method to get value; cellname is A1,A2, or B1,B2 etc...in excel.
        static string excel_getValue(string cellname)
        {
            string value = string.Empty;
            try
            {
                value = objsheet.get_Range(cellname).get_Value().ToString();
            }
            catch
            {
                value = "";
            }

            return value;
        }

        //Method to close excel connection
        static void excel_close()
        {
            if (appExcel != null)
            {
                try
                {
                    newWorkbook.Close();



         System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook.ActiveSheet);   
               System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel.ActiveWorkbook);

   System.Runtime.InteropServices.Marshal.ReleaseComObject(appExcel);
                    appExcel = null;
                    objsheet = null;
                }
                catch (Exception ex)
                {
                    appExcel = null;
                    Console.WriteLine("Unable to release the Object " + ex.ToString());
                }
                finally
                {
                    GC.Collect();
                }
            }
        }

提前致谢

编辑:我现在分开读取两个 Excel 文件并将信息放入列表中。现在我只想将最终的 Excel 文档保存为另一个名为 xxx.xlsx 的文档

Edit2:通过将其放入我的 excel_init 函数中来修复它:

static void excel_init(String path)
        {
            appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();

            if (System.IO.File.Exists(path))
            {
                // then go and load this into excel
                //newWorkbook_Second = appExcel.Workbooks.Open(path, true, true);
                newWorkbook_First = appExcel.Workbooks.Open(path, true, true);
                objsheet = (_Worksheet)appExcel.ActiveWorkbook.ActiveSheet;
            }
            else
            {
                try
                {
                    appExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                    appExcel.Visible = true;
                    newWorkbook_First = appExcel.Workbooks.Add(1);
                    objsheet = (Microsoft.Office.Interop.Excel.Worksheet)newWorkbook_First.Sheets[1];
                }
                catch (Exception e)
                {
                    Console.Write("Error");
                }
                finally
                {
                }
            }

        }

编码不太好...但它有效...


您需要一个 FileManager 类来负责读取和写入文件。然后使用文件管理器的实例读取多个文件并写入一个文件。但是,读取路径和写入路径必须不同。

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;

namespace MultipleExcelReadWriteExample
{
    public class Program
    {
        private static void Main(string[] args)
        {
            // create a instance of the file manager
            var fileManager = new FileManager();

            // add the list of file paths to collection
            fileManager.ListOfWorkbooksPath.Add("workBookToRead1", @"C:\ExcelFiles\WorkbookToRead1.xlsx");
            fileManager.ListOfWorkbooksPath.Add("workBookToRead2", @"C:\ExcelFiles\WorkbookToRead2.xlsx");
            fileManager.ListOfWorkbooksPath.Add("workBookToRead3", @"C:\ExcelFiles\WorkbookToRead3.xlsx");
            fileManager.ListOfWorkbooksPath.Add("workBookToWrite1", @"C:\ExcelFiles\WorkbookToWrite1.xlsx");

            // Open the excel app
            fileManager.OpenExcelApp();
            // open all the workbooks
            fileManager.OpenWorkbooks();

            // Do some data transfer here!
            int index = 1;
            foreach (var workbook in fileManager.ListOfWorkbooks)
            {
                if (workbook.Key.Contains("workBookToRead"))
                {
                    // get the worksheet to read
                    var readWorksheet = workbook.Value.Worksheets["Sheet1"] as Worksheet;

                    // get the writing workbook
                    Workbook workbookToWrite = fileManager.ListOfWorkbooks["workBookToWrite1"];
                    // get the worksheet to write
                    var writeWorksheet = workbookToWrite.Worksheets["Sheet" + index] as Worksheet;
                    //TODO: create a new sheet if doesn't exist

                    for (int column = 1; column <= 10; column++)
                    {
                        for (int row = 1; row <= 10; row++)
                        {
                            // read the data from the worksheet
                            Tuple<dynamic, dynamic> data = fileManager.ReadFromCell(readWorksheet, column, row);

                            // write the data to the worksheet
                            fileManager.WriteToCell(writeWorksheet, column, row, data);
                        }
                    }
                }

                index++;
            }

            // save all workbooks
            fileManager.SaveAllWorkbooks();
            // close all workbooks
            fileManager.CloseAllWorkbooks();
            // close the excel app
            fileManager.CloseExcelApp();

            Console.WriteLine("Press key to continue");
            Console.ReadKey();
        }
    }


    public class FileManager
    {
        private Application _excelApp;

        /// <summary>
        ///     Basic c'tor
        /// </summary>
        public FileManager()
        {
            ListOfWorkbooksPath = new Dictionary<string, string>();
            ListOfWorkbooks = new Dictionary<string, Workbook>();
        }

        /// <summary>
        ///     List of workbook to read, with their name and path
        /// </summary>
        public Dictionary<string, string> ListOfWorkbooksPath { get; set; }

        public Dictionary<string, Workbook> ListOfWorkbooks { get; set; }

        /// <summary>
        ///     Finalizer
        /// </summary>
        ~FileManager()
        {
            if (_excelApp != null)
            {
                _excelApp.Quit();
                Marshal.ReleaseComObject(_excelApp);
            }

            _excelApp = null;
        }

        /// <summary>
        ///     Open the Excel application
        /// </summary>
        public void OpenExcelApp()
        {
            _excelApp = new Application();
        }

        /// <summary>
        ///     Open list of workbooks for given path
        /// </summary>
        public void OpenWorkbooks()
        {
            foreach (var item in ListOfWorkbooksPath)
            {
                if (!ListOfWorkbooks.ContainsKey(item.Key))
                {
                    Workbook workbook = _excelApp.Workbooks.Open(item.Value);
                    ListOfWorkbooks.Add(item.Key, workbook);
                }
            }
        }

        /// <summary>
        ///     Read a cell and return the value and the cell format
        /// </summary>
        /// <param name="worksheet">The worksheet to read the value from.</param>
        /// <param name="column">The column number to read the value from.</param>
        /// <param name="row">The row number to read the value from.</param>
        /// <returns>The value and cell format.</returns>
        public Tuple<dynamic, dynamic> ReadFromCell(Worksheet worksheet, int column, int row)
        {
            var range = worksheet.Cells[row, column] as Range;

            if (range != null)
            {
                dynamic value = range.Value2; // get the value of the cell
                dynamic format = range.NumberFormat; // get the format of the cell
                return new Tuple<dynamic, dynamic>(value, format);
            }

            return null;
        }

        /// <summary>
        ///     Write the data to a cell in worksheet.
        /// </summary>
        /// <param name="worksheet">The worksheet to write the value.</param>
        /// <param name="column">The column number to write the value.</param>
        /// <param name="row">The row number to write the value.</param>
        /// <param name="data">The data to be written to a cell; this is a Tuple that contains the value and the cell format.</param>
        public void WriteToCell(Worksheet worksheet, int column, int row, Tuple<dynamic, dynamic> data)
        {
            var range = worksheet.Cells[row, column] as Range;

            if (range != null)
            {
                range.NumberFormat = data.Item2; // set the format of the cell
                range.Value2 = data.Item1; // set the value of the cell
            }
        }


        /// <summary>
        ///     Save all workbooks
        /// </summary>
        public void SaveAllWorkbooks()
        {
            foreach (var workbook in ListOfWorkbooks)
            {
                SaveWorkbook(workbook.Value);
            }
        }

        /// <summary>
        ///     Save single workbook
        /// </summary>
        /// <param name="workbook"></param>
        public void SaveWorkbook(Workbook workbook)
        {
            workbook.Save();
        }

        /// <summary>
        ///     Close all workbooks
        /// </summary>
        public void CloseAllWorkbooks()
        {
            foreach (var workbook in ListOfWorkbooks)
            {
                CloseWorkbook(workbook.Value);
            }

            ListOfWorkbooks.Clear();
        }

        /// <summary>
        ///     Close single workbook
        /// </summary>
        /// <param name="workbook"></param>
        public void CloseWorkbook(Workbook workbook)
        {
            workbook.Close();
        }

        /// <summary>
        ///     Close the Excel Application
        /// </summary>
        public void CloseExcelApp()
        {
            if (_excelApp != null)
            {
                _excelApp.Quit();
            }

            _excelApp = null;
            ListOfWorkbooksPath.Clear();
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从多个Excel文档中读取数据并将其写入另一个Excel文档中 的相关文章

  • C++ 中本地类中的静态成员变量?

    我知道我们不能宣布static本地类中的成员变量 但其原因尚不清楚 那么请问有人可以解释一下吗 另外 为什么我们不能访问非static函数内部定义的变量 内部已经定义了局部类 直接在局部类成员函数中 在下面给出的代码中 int main i
  • 启动时出现 OData v4 错误:找不到段“Whatever”的资源

    我正在构建新的 v4 服务 一切进展顺利 直到我为新模型 实体添加了新控制器 并在启动站点进行测试运行时收到此错误 控制器似乎编码正确 就像其他控制器一样 控制器 CustomersOData 中的操作 GetFeed 上的路径模板 Cus
  • 如何将 #ifdef DEBUG 添加到 Xcode?

    我的项目中有一些代码永远不应该在发布版本中使用 但在测试时很有用 我想做这样的事情 ifdef DEBUG Run my debugging only code endif 在 Xcode 4 中哪里添加 DEBUG 设置 我尝试将其放入
  • 如何修复此错误“GDI+ 中发生一般错误”?

    从默认名称打开图像并以默认名称保存 覆盖它 我需要从 Image Default jpg 制作图形 将其放在 picturebox1 image 上并在 picurebox1 上绘制一些图形 它有效 这不是我的问题 但我无法保存 pictu
  • 在新的浏览器进程中打开 URL

    我需要在新的浏览器进程中打开 URL 当浏览器进程退出时我需要收到通知 我当前使用的代码如下 Process browser new Process browser EnableRaisingEvents true browser Star
  • 将 System.Windows.Input.KeyEventArgs 键转换为 char

    我需要将事件参数作为char 但是当我尝试转换 Key 枚举时 我得到的字母和符号与传入的字母和符号完全不同 如何正确地将密钥转换为字符 这是我尝试过的 ObserveKeyStroke this new ObervableKeyStrok
  • 使用 python 只读取 Excel 中的可见行

    我想只读取 python 中 Excel 工作表中的可见行 输入 Excel表 所以当我过滤时 作为 python 中的输出 在本例中我将仅获得可见数据 1 行 这是我的代码 from openpyxl import load workbo
  • 在 C# 中循环遍历文件文件夹的最简单方法是什么?

    我尝试编写一个程序 使用包含相关文件路径的配置文件来导航本地文件系统 我的问题是 在 C 中执行文件 I O 这将是从桌面应用程序到服务器并返回 和文件系统导航时使用的最佳实践是什么 我知道如何谷歌 并且找到了几种解决方案 但我想知道各种功
  • 如何在 Linq 中获得左外连接?

    我的数据库中有两个表 如下所示 顾客 C ID city 1 Dhaka 2 New york 3 London 个人信息 P ID C ID Field value 1 1 First Name Nasir 2 1 Last Name U
  • Rx 中是否有与 Task.ContinueWith 运算符等效的操作?

    Rx 中是否有与 Task ContinueWith 运算符等效的操作 我正在将 Rx 与 Silverlight 一起使用 我正在使用 FromAsyncPattern 方法进行两个 Web 服务调用 并且我想这样做同步地 var o1
  • 如何对 Web Api 操作进行后调用?

    我创建了一个 Web API 操作 如下所示 HttpPost public void Load string siteName string providerName UserDetails userDetails implementat
  • .NET中的LinkedList是循环链表吗?

    我需要一个循环链表 所以我想知道是否LinkedList是循环链表吗 每当您想要移动列表中的 下一个 块时 以循环方式使用它的快速解决方案 current current Next current List First 电流在哪里Linke
  • 用于 C# 的 TripleDES IV?

    所以当我说这样的话 TripleDES tripledes TripleDES Create Rfc2898DeriveBytes pdb new Rfc2898DeriveBytes password plain tripledes Ke
  • Excel VBA 自动过滤子字符串

    我的 Excel 中有多行 其中 D 列为 TDM 02 Bundle Rehoming 5 NE TDM 02 Bundle Rehoming 23 NE IP 02 Bundle Rehoming 7 NE 等 请注意 大多数情况下 N
  • 父子进程隔离和子进程列表

    请阅读以下模板 PID Status LPID 10 Closed 25 11 Open 25 31 Open 31 25 Closed 25 54 Open 31 17 Open 17 20 Closed 31 88 closed 77
  • 如何在按钮单击时模拟按键 - Unity

    我对 Unity 中的脚本编写非常陌生 我正在尝试创建一个按钮 一旦单击它就需要模拟按下 F 键 要拾取一个项目 这是我当前的代码 在编写此代码之前我浏览了所有统一论坛 但找不到任何有效的东西 Code using System Colle
  • 有没有办法强制显示工具提示?

    我有一个验证字段的方法 如果无法验证 该字段将被清除并标记为红色 我还希望在框上方弹出一个工具提示 并向用户显示该值无效的消息 有没有办法做到这一点 并且可以控制工具提示显示的时间 我怎样才能让它自己弹出而不是鼠标悬停时弹出 If the
  • 英特尔 Pin 与 C++14

    问题 我有一些关于在 C 14 或其他 C 版本中使用英特尔 Pin 的问题 使用较新版本从较旧的 C 编译代码很少会出现任何问题 但由于 Intel Pin 是操作指令级别的 如果我使用 C 11 或 C 14 编译它 是否会出现任何不良
  • Linq-to-entities,在一个查询中获取结果+行数

    我已经看到了有关此事的多个问题 但它们已经有 2 年 或更长 的历史了 所以我想知道这方面是否有任何变化 基本思想是填充网格视图并创建自定义分页 所以 我还需要结果和行数 在 SQL 中 这将类似于 SELECT COUNT id Id N
  • 防止在工厂方法之外实例化对象

    假设我有一个带有工厂方法的类 class A public static A newA Some code logging return new A 是否可以使用 a 来阻止此类对象的实例化new 那么工厂方法是创建对象实例的唯一方法吗 当

随机推荐