0

我正在尝试用 C# 编写一个小的 xlsx 到 csv(字符分隔值)程序(因为 windows 用户)。

我想成为一个逗号分隔值,但不是逗号,而是每个单元格都用不可见字符分隔,因为这是 hive 中的默认字符(我相信是'\001')。

如何将此字符写入 C# 中的文件?我试过 "\001" , @"\001", "\uFEFF" 但没有成功..任何指针?

这是代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Excel = Microsoft.Office.Interop.Excel;
namespace excel2csv
{

    class ExcelConverter
    {

        static void openExcel(string path,String outpath,String delim)
        {
            Excel.Application excelApp = new Excel.Application();
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(path, 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);

            foreach(Excel.Worksheet worksheet in excelWorkbook.Worksheets){
                System.IO.StreamWriter file = new System.IO.StreamWriter(outpath+worksheet.Name+".csv", true);
                Excel.Range usedRange = worksheet.UsedRange;
                int nRows = usedRange.Rows.Count;
                int nCols = usedRange.Columns.Count;
                for (int iRow = 1; iRow <= nRows; iRow++)
                {
                    String line = "";
                    for (int iCount = 1; iCount <= nCols; iCount++)
                    {
                        usedRange= (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[iRow, iCount];
                        line += usedRange.Text + delim;
                       // Console.ReadLine();
                    }
                    Console.WriteLine();

                    file.WriteLine(line);
                }

                Console.WriteLine(worksheet.Name);
                file.Close();

            }
            Console.Read();
            excelWorkbook.Close();

        }


        static void Main(string[] args)
        {
            String path = @"C:\file.xlsx";
            String outpath = @"file";
            String delim = @"\001";
            openExcel(path,outpath, delim);
        }


    }
}
4

2 回答 2

0

顺便说一句,答案如下:

string delim = "\x01";
于 2013-11-05T15:06:44.573 回答
0

尝试这个 :

            String str = @"\001";
            System.IO.File.WriteAllText(filepath, str);
于 2013-11-01T16:33:43.970 回答