简体   繁体   English

.NET - 如何将多个 CSV 文件合并为一个 MS Excel 文件,其中包含多个选项卡

[英].NET - How to combine multiple CSV files into one MS Excel file with multiple tabs

I have a .NET app that makes multiple CSV file like我有一个 .NET 应用程序,可以制作多个 CSV 文件,例如

1.csv
2.csv
3.csv
.
.
.

I am trying to turn them into a single.xlsx file with data of each CSV in a separate tab.我试图将它们变成一个 single.xlsx 文件,每个 CSV 的数据都在单独的选项卡中。 I've come across a few NuGet packages that let me do that, but they all seem to have quite expensive licenses.我遇到了一些 NuGet 包,可以让我这样做,但它们似乎都有相当昂贵的许可证。 Then I found Microsoft.Office.Interop.Excel which, for the life of me, I cannot figure out.然后我找到了Microsoft.Office.Interop.Excel ,对于我来说,我无法弄清楚。 Is there an easy way to combine multiple CSV files into one MS Excel file with multiple tabs?有没有一种简单的方法可以将多个 CSV 文件组合成一个带有多个选项卡的 MS Excel 文件?

You don't need any library to do that.你不需要任何图书馆来做到这一点。 CSV files are just text files with a certain format. CSV 文件只是具有特定格式的文本文件。 All you need to do is to create a file and copy the other files into it:您需要做的就是创建一个文件并将其他文件复制到其中:

Sorry for misreading the question.抱歉误读了这个问题。 Here is a sample with the NPOI library usage:以下是 NPOI 库用法示例:

var files = Directory.GetFiles(DownloadPath);
var combinedFile = Path.Combine(DownloadPath, "Combined.xlsx");
using var target = new FileStream(combinedFile, FileMode.Create, FileAccess.Write);
IWorkbook workbook = new XSSFWorkbook();
var seperator = ";";

foreach (var file in files)
{
    ISheet sheet = workbook.CreateSheet(file);
    using var sourceFile = new FileStream(file, FileMode.Open, FileAccess.Read);
    using TextReader reader = new StreamReader(sourceFile);
    var line = await reader.ReadLineAsync();
    var i = 0;
    while (!string.IsNullOrEmpty(line))
    {
        var row = sheet.CreateRow(i++);
        var values = line.Split(seperator);
        for (int j = 0; j < values.Length; j++)
        {
            var cell = row.CreateCell(j);
            cell.SetCellValue(values[j]);
        }
    } 
}

workbook.Write(target);

Please also notice that it's just a sample.另请注意,这只是一个示例。 You should check the documents for detailed info.您应该查看文档以获取详细信息。

If you don't find any free package to do so, I've found EPPlus quite straightforward to use.如果您找不到任何免费的 package 来这样做,我发现 EPPlus 使用起来非常简单。 They have a NonCommercial license if you want to try it.如果您想尝试,他们有非商业许可。 For commercial apps it has a price.对于商业应用程序,它是有代价的。

To make the tabs, doing ExcelPackage.Workbook.Worksheets.Add("Tab Name");要制作选项卡,请执行ExcelPackage.Workbook.Worksheets.Add("Tab Name"); you can create a tab and then doing tab.Cells[row, colum].Value = "X" you can enter the info you need.您可以创建一个选项卡,然后执行tab.Cells[row, colum].Value = "X"您可以输入所需的信息。

There are multiple ways to do this.有多种方法可以做到这一点。 One way is to use Epplus package. Another one is to use Interop.Excel which is quite straightforward.一种方法是使用 Epplus package。另一种方法是使用 Interop.Excel,这非常简单。 With Interop.Excel you have more opportunities (such as you could do anything you can do manually using Excel + create add in etc).使用 Interop.Excel 你有更多的机会(比如你可以做任何你可以使用 Excel 手动做的事情 + 创建插件等)。 Anyway, using Interop.Excel, you could use CopyFromRecordset() or even better if your files persistent is QueryTables.Add().无论如何,使用 Interop.Excel,您可以使用 CopyFromRecordset() 或者如果您的文件持久性是 QueryTables.Add() 则更好。 Here is a sample using CopyFromRecordset:以下是使用 CopyFromRecordset 的示例:

using ADODB;
using Excel=Microsoft.Office.Interop.Excel;

void Main()
{
    Excel.Application xl = new Excel.Application();
    var wb = (Excel.Workbook)xl.Workbooks.Add();
    //xl.Visible = true;

    ConnectionClass cn = new ConnectionClass();
    string path = @"c:\temp\myCSVFiles";
    string[] filenames = { "1.csv", "2.csv", "3.csv", "4.csv" };
    string connectionString = $@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={path};Extended Properties=""text;HDR=Yes;FMT=Delimited"";";
    cn.Open(connectionString, "", "", 0);
    
    for (int i = 0; i < filenames.Length; i++)
    {
        if (i > 0 && wb.Worksheets.Count < i + 1) {
            wb.Worksheets.Add(After: wb.Worksheets[i]);
        }
        var ws = (Excel.Worksheet)wb.Worksheets[i+1];

        RecordsetClass rs = new RecordsetClass();
        string filename = filenames[i];
        rs.Open($@"select * from {filename}",
            cn,
            CursorTypeEnum.adOpenUnspecified,
            LockTypeEnum.adLockUnspecified, 0);

        ws.Activate();
        Excel.Range rng = ws.Range["A1"];
        for (int j = 0; j < rs.Fields.Count; j++)
        {
            rng.Offset[0, j].Value2 = rs.Fields[j].Name;
            rng.Offset[0, j].Font.Bold = true;
        }

        rng.Offset[1, 0].CopyFromRecordset(rs);
        ws.UsedRange.Columns.AutoFit();
        rs.Close();
    }
    cn.Close();
    wb.SaveAs(@"c:\temp\MyCSVStore.xlsx");
    wb.Close(SaveChanges:true);
    
    
    xl.Quit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM