当前位置: 首页 > 知识库问答 >
问题:

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

曹和正
2023-03-14

目前,我只能阅读一个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();
                }
            }
        }
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
                {
                }
            }

        }

不是很好的编码...但它有效...

共有1个答案

黄流觞
2023-03-14

您需要一个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();
        }
    }
}
 类似资料:
  • 如何用Java将一个Excel的文件的数据读取到另一个Excel中? 我有两个excel文件,希望将A文件中的数据合并在B文件中。有没有推荐的方案

  • 档案员。txt包含两类员工的详细信息,即月薪和小时津贴。如果是月薪员工,则该文件包含名字、姓氏、性别、职级、类型和基本工资,如果是小时薪员工,则包含小时工资和工作小时数。该文件的示例如下所示: 约翰·史密斯M经理每月45000.00 Sunil Bates M高级每小时700.00 45 梁爱娃F警官每月30500.00 我要写一个程序,会看每个员工,计算奖金占基本工资的百分比,对于一个按小时计酬

  • 问题内容: 我有一个包含不同列数的Excel文件,我想使用Python遍历该文件的某些列(从其标题行值开始),然后将这些列写入(复制)到另一个Excel文件中。 请问有关如何执行此操作的任何示例? 问题答案: 以下是一些可供选择的选项: xlwt(编写xls文件) xlrd(读取xls / xlsx文件) openpyxl(读取/写入xlsx文件) xlsxwriter(写入xlsx文件) 如果只

  • 我想从一个目录中读取几个excel文件到pandas中,并将它们连接到一个大的数据帧中。不过我还没弄明白。我需要一些关于for循环和构建级联数据帧的帮助:

  • 本文向大家介绍Python将多个excel文件合并为一个文件,包括了Python将多个excel文件合并为一个文件的使用技巧和注意事项,需要的朋友参考一下 利用Python,将多个excel文件合并为一个文件 思路 利用python xlrd包读取excle文件,然后将文件内容存入一个列表中,再利用xlsxwriter将内容写入到一个新的excel文件中。 完整代码 源文件excel1: 源文件e

  • 我有从多个文件读取并写入多个文件的Spring批处理配置。是否可以只写入从多个读取的一个文件。假设我收到巨大的XML文件,我将XML拆分为小文件并使用分区器并行读取小文件。但我需要将从不同的小xml文件读取的所有数据写入一个输出文件。Spring批处理是否可以做到这一点?我知道通过使写入器同步是可能的,但我正在寻找任何其他可能的方式作业配置 我得到错误组织。springframework。一批项目