简体   繁体   中英

Interop.Excel UTF-8 encoding when saving file

I'm having an issue saving an Excel file as a CSV with UTF-8 encoding.

Because I have non standard characters (different language) in my Excel document it caused issues when saved as a CSV. This was solved here by setting the web options encoding to UTF-8.

I am creating a basic C# program that parses data from an Excel file and saves it in CSV format but I cant get it to save using the UTF-8 encoding.

I am using Microsoft.Office.Interop.Excel to work with the Excel files.

This is my code:

private Excel.Application application = new Excel.Application { Visible = false };
private Excel.Workbook Workbook = application.Workbooks.Open(OrigionalFileUrl);
Workbook.SaveAs(NewFileUrl);

I have tried setting

application.DefaultWebOptions.Encoding = MsoEncoding.msoEncodingUTF8;

but it doesnt work and the CSV file that I get is always a mess when it comes to sections with special characters.

Thanks!

I believe you want to do that on the workbook level, not on the application. Also, it's possible because you didn't include the file format as CSV that the SaveAs is using the native format but only changing the file extension.

Try these and see if they address your issue:

Workbook.WebOptions.Encoding = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
Workbook.SaveAs(NewFileUrl, XlFileFormat.xlCSV);

The proposed solution didn't work for me. But according to the documentation there is now a
XlFileFormat for CSV-UTF8:

XlFileFormat.xlCSVUTF8

https://docs.microsoft.com/en-us/office/vba/api/excel.xlfileformat

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