如何将带有某个标记分隔符的文本文件转换为xls或xlsx文件? [英] How do I convert a text file with some marker delimiter to a xls or xlsx file?

查看:199
本文介绍了如何将带有某个标记分隔符的文本文件转换为xls或xlsx文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本文件,看起来像这个。文件中的@@@标记新列的开头。我想使用Microsoft Excel 14.0对象库或任何其他免费库将此文件转换为excel文件,如



有人可以帮忙吗?



我的尝试:



我对此完全空白。我正在考虑在文本文件中使用 split 方法获取每行和每列的内容,但不知道如何实现它

I have some text files which looks like this. The @@@ in the file marks the start of a new column. I want to use Microsoft Excel 14.0 Object Library or any other free library to convert this file to a excel file like this.

Can anyone help?

What I have tried:

I'm totally blank on this. I was thinking about using the split method in the text file to get the contents for each row and column but have no clue how to implement it

推荐答案

您需要读取每一行并在@@@字符串之间拆分字段。然后,您可以使用 Microsoft创建新的Excel文件.Office.Interop.Excel命名空间| Microsoft Docs [ ^ ]
You would need to read each line and split the fields between the "@@@" strings. You can then create the new Excel file by using the Microsoft.Office.Interop.Excel Namespace | Microsoft Docs[^]


这显示了将信息保存到Excel工作簿的基础知识。您只需根据自己的特定要求进行修改即可。如果您不想要列标题,那么只需省略第一个循环,并将行号保留为1.

This shows the basics of saving information to an Excel workbook. You just need to modify it to your own specific requirements. If you do not want column headers then just omit the first loop, and leave the row number equal to 1.
using Excel = Microsoft.Office.Interop.Excel;


void Save()
{
    //Create an Excel application instance
    Excel.Application excelApp = new Excel.Application();

    //Create an Excel workbook instance and open it from the predefined location
    Excel.Workbook excelWorkBook = excelApp.Workbooks.Add(Type.Missing);
    Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add(Type.Missing);
    excelWorkSheet.Name = "mydata";

    int row = 1;
    int column = 1;
    for // a loop for all the column names
    {
        // row 1 contains column headers
        excelWorkSheet.Cells[row, column] = // text of the column header
        ++column;
    }

    int row = 2;    // leave as 1 if no column headers
    foreach (string str in // the lines of text)
    {
        string[] fields = str.Split(new char[]{ '@', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        for (column = 0; column < fields.length; ++column)
        {
            excelWorkSheet.Cells[row, column + 1] = fields[column];
        }
        row++;
    }
    excelWorkBook.SaveAs(fileName);
    excelWorkBook.Close();
    excelApp.Quit();
}


这篇关于如何将带有某个标记分隔符的文本文件转换为xls或xlsx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆