Reputation: 149
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!
Upvotes: 5
Views: 13303
Reputation: 385
I had such as issue when I worked with the EPPlus library and tried to save an Excel file with characters in a different langauge into CSV file. This is how I solved it using UTF-8 encoding:
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var excelPackage = new ExcelPackage())
{
try
{
var worksheet =
excelPackage.Workbook.Worksheets.Add("Sheet1");
// some code in here
ExcelOutputTextFormat excelOutputTextFormat = new
ExcelOutputTextFormat();
excelOutputTextFormat.Encoding = Encoding.UTF8;
worksheet
.Cells["A1:AA500"]
.SaveToText(new FileInfo($"{filePath}.csv"),
excelOutputTextFormat);
Upvotes: 0
Reputation: 895
The proposed solution didn't work for me. But according to the documentation there is now a
XlFileFormat for CSV-UTF8:
XlFileFormat.xlCSVUTF8
https://learn.microsoft.com/en-us/office/vba/api/excel.xlfileformat
Upvotes: 0
Reputation: 16377
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);
Upvotes: 5