Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 822
Yuval Feldman Avatar asked Dec 24 '15 14:12

Yuval Feldman


People also ask

What encoding does Excel save CSV in?

In Excel 2016 and later versions, you can save a file in the CSV format with UTF-8 encoding directly: In the target worksheet, click File > Save As or press the F12 key. In the Save As dialog box, select CSV UTF-8 (comma delimited) (*. csv) from the Save as type drop down.


1 Answers

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);
like image 151
Hambone Avatar answered Oct 23 '22 03:10

Hambone