简体   繁体   中英

Microsoft.Office.Interop.Excel - opening csv with semicolon delimiter

I have read Microsoft.Office.Interop.Excel - *.csv file opening but it does not work for me and I don't know why.

First I tried only using the optional parameters I need like this:

Excel.Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(path, Delimiter:";");

It opens the csv but separates at the comma.

Then I tried like in the referenced thread above and it does not separate at all.

Excel.Application xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Open(path,0,false,5, "","",false,Excel.XlPlatform.xlWindows,";",true,false,0,true,false,false);

Here is some sample data I used:

2,138;2,066;2,022;2,076;0,297;;;0,770;1,898;1,864;1,798;1,859;1,715;20,032;8,599;0,039;;;0,336;Iteration: 5 of 500
0,298;0,295;0,298;0,297;0,297;;;0,302;0,296;0,296;0,297;0,297;0,299;0,300;0,296;0,037;;;0,409;Iteration: 6 of 500
0,297;0,299;0,296;0,297;0,311;;;0,295;0,295;0,295;0,295;0,295;0,295;0,306;0,306;0,039;;;0,372;Iteration: 7 of 500
0,299;0,298;0,295;0,297;0,295;;;0,294;0,307;0,295;0,295;0,296;0,297;0,296;0,295;0,040;;;0,368;Iteration: 8 of 500

Has anyone an idea what im doing wrong?

When I open the csv file with a double click (excel standard program to open csv) it formats it as I want. With the semicolon as delimiter. I probably have set it in the properties once.

Try OpenText :

Excel.Application ex = new Excel.Application();

Excel.Workbooks wbs = ex.Workbooks;

wbs.OpenText(path,
    DataType:Excel.XlTextParsingType.xlDelimited, 
    Semicolon: true);

https://docs.microsoft.com/en-us/dotnet/api/microsoft.office.interop.excel.workbooks.open?view=excel-pia

Format Object

Optional Object. If Microsoft Excel is opening a text file, this argument specifies the delimiter character, as shown in the following table. If this argument is omitted, the current delimiter is used.

...

Delimiter Object

Optional Object. If the file is a text file and the Format argument is 6, this argument is a string that specifies the character to be used as the delimiter. For example, use Chr(9) for tabs, use "," for commas, use ";" for semicolons, or use a custom character. Only the first character of the string is used.

So your open statement should be: xlWorkBook = xlApp.Workbooks.Open(path, Format:6, Delimiter:";");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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