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

C# 从多个excel文档中读取数据并将其写入另一个excel文档,c#,excel,C#,Excel,目前,我只能读入一份excel文档,并用我得到的代码编写相同的文档。现在我想读取多个excel文档,并将数据写入其中。现在我在一个文档中得到了一个明确的代码,但这不是我想要的。我理解我现在得到的代码的结构,所以我更愿意坚持下去。如何使用excel\u init函数和excel\u getValue函数实现这一点 以下是我到目前为止所拥有的: static void Main(string[] args) { excel_init("C:\\Users\\A

目前,我只能读入一份excel文档,并用我得到的代码编写相同的文档。现在我想读取多个excel文档,并将数据写入其中。现在我在一个文档中得到了一个明确的代码,但这不是我想要的。我理解我现在得到的代码的结构,所以我更愿意坚持下去。如何使用
excel\u init
函数和
excel\u 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();
                }
            }
        }

不是很好的编码。。。但它是有效的…

您可以打开多个工作簿

newWorkbook_Second = appExcel.Workbooks.Open(pathforanotherworkbook, true, true);

您需要一个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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Runtime.InteropServices;
使用Microsoft.Office.Interop.Excel;
命名空间MultipleExcelReadWriteExample
{
公共课程
{
私有静态void Main(字符串[]args)
{
//创建文件管理器的实例
var fileManager=newfilemanager();
//将文件路径列表添加到集合
fileManager.listofWorkbookPath.Add(“WorkbookStoreAD1”,@“C:\ExcelFiles\WorkbookStoreAD1.xlsx”);
fileManager.listofWorkbookPath.Add(“WorkbookStoreAD2”,@“C:\ExcelFiles\WorkbookStoreAD2.xlsx”);
fileManager.listofWorkbookPath.Add(“WorkbookStoreAD3”,@“C:\ExcelFiles\WorkbookStoreAD3.xlsx”);
fileManager.ListofWorkbookPath.Add(“workBookToWrite1”,@“C:\ExcelFiles\workBookToWrite1.xlsx”);
//打开excel应用程序
fileManager.OpenExcelApp();
//打开所有的工作簿
fileManager.OpenWorkbooks();
//在这里做一些数据传输!
int指数=1;
foreach(fileManager.ListOfWorkbooks中的var工作簿)
{
if(workbook.Key.Contains(“workBookToRead”))
{
//让学生阅读工作表
var readWorksheet=workbook.Value.Worksheets[“Sheet1”]作为工作表;
//拿到写作练习册
工作簿workbookToWrite=fileManager.ListOfWorkbooks[“workBookToWrite1”];
//让工作表来写
var writeWorksheet=workbookToWrite.Worksheets[“Sheet”+索引]作为工作表;
//TODO:如果不存在,则创建新图纸

对于(int column=1;column不使用需要安装Excel的Interop,而是直接使用像EPPlus或Open XML SDK这样的库。这需要做大量的更改吗?我不太擅长这一点。我很高兴看到您使用
ReleaseComObject
来发布Excel应用程序,但您还需要对您引用的每个其他COM对象都这样做引用-
工作簿
活动工作簿
活动工作表
,等等。甚至反对你“双重”引用-
appExcel.ActiveWorkbook.ActiveSheet
-你需要同时发布
appExcel.ActiveWorkbook
appExcel.ActiveWorkbook.ActiveSheet
。谢谢你的提示!我更改了代码:)@wouter-读一读:谢谢,我会解决这个问题的!如果我被这个解决方案困住了,我会发表评论。我真的不知道怎么做,你能以任何方式帮助我编写代码吗?是的,我会给你写一个示例代码,稍后再发布给你。正如我承诺的,请参见答案中的示例aboce。
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();
        }
    }
}