0

我面临一个关于 excel 写作的问题。下面是问题 - 我有一个要求,我有多个 excel 工作表,并且每个 excel 文件可能有多个工作表。所以,我需要用多个单独的工作表写一个 excel例如,假设我有 3 个带有 Sheet1 的 Excel 文件 File1.xlsx,带有 Sheet2 的 File2.xlsx 和带有多个 Sheet3 和 Sheet4 的文件 3。在每个工作表中,数据类似于 3 列(姓名、员工 ID、MobNo)所以,输出将是带有多个工作表 Sheet1、Sheet2、Sheet3 和 Sheet4 的单个文件 Result.xlsx。

请在没有任何第三方工具(如 Spire.xl)的情况下共享代码。我需要以编程方式执行此操作。以下是代码 -

        string inputPathFirstExcel = 
        @"C:\MyData\ExcelWritingApp\File1.xlsx";
        string inputPathSecondExcel = @"C:\\ExcelWritingApp\File2.xlsx";

        string[] ColumnData = { };
        Excel.Application xlApp = null;
        Excel.Workbook xlWorkBook = null;
        Excel.Worksheet xlWorkSheet = null;
        Excel.Range xlrange = null;



        xlApp = new Excel.Application();
        xlApp.Visible = false;
        xlWorkBook = xlApp.Workbooks.Open(inputPathFirstExcel);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Sheets[1];
        xlrange = xlWorkSheet.UsedRange;
        object missing = Type.Missing;
        Excel.Application oXL = new Excel.Application();
        oXL.Visible = false;

        Excel.Workbook oWB = oXL.Workbooks.Add(missing);

        Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
            oSheet.Name = "Sheet1";

            Microsoft.Office.Interop.Excel.Range xlRange = xlWorkSheet.UsedRange;
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Employee");
            dt.Columns.Add("MobNo");

            int rowCount = xlRange.Rows.Count;
            int colCount = xlRange.Columns.Count;

            for (int i = 1; i <= colCount; i++)
            {
                oSheet.Cells[1, i] = dt.Columns[i - 1].ToString().ToUpper() + "\t";
            }

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 1; j <= colCount; j++)
                {

                    oSheet.Cells[i + 2, j] = Convert.ToString((xlRange.Cells[i + 2, j] as Excel.Range).Value2);
                }
            }

            string fileName = @"C:\Result.xlsx";
            oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook,
                missing, missing, missing, missing,
                Excel.XlSaveAsAccessMode.xlNoChange,
                missing, missing, missing, missing, missing);
4

0 回答 0