How to insert data to specific cell in csv and save the csv file using c#

Viewed 368

Im using the below C# code to insert the data in different cells in a CSV file and should be able to save it. When i execute the code, the data in individual cells get merged into single cell and file is changed to Read only mode. please support what can be done to insert data in specific cells in CSV file and to save it without disturbing the format and alignment of the data.

Code:

Excel.Application excelAppObj = new Excel.Application();
excelAppObj.DisplayAlerts = false;
                
//Open the excel work book
Excel.Workbook workBook = excelAppObj.Workbooks.Open("D:\\NAL_SSR_stats_stn.CSV", 0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, 0, false, false);
                
//Get the first sheet of the selected work book
Excel.Worksheet worksheet = (Excel.Worksheet)workBook.Worksheets.get_Item(1);
                
//Write 20 in Cell - C3
worksheet.Cells[1, 3] = "AP";
worksheet.Cells[1, 4] = "APC";
worksheet.Cells[1, 5] = "NOC";
worksheet.Cells[1, 6] = "NOP";
worksheet.Cells[1, 7] = "NOQ";
worksheet.Cells[1, 8] = "NOE";
                
//Save work book (.csv format)
workBook.SaveAs("D:\\NAL_SSR_stats_stn.CSV", Excel.XlFileFormat.xlCSVWindows, null, null, true, false, Excel.XlSaveAsAccessMode.xlShared, false, false, null, null, null);
1 Answers

I am assuming that you are using Excel to open your CSV file. If you open your CSV in another text editor such as notepad you'll notice that the file simply contains data separated by commas. A CSV does not contain format or styling information. If you open a CSV in Excel you can temporarily change the format which may be cached, but if anyone else opens that file it won't have the formatting that you want. If you want to specify your formatting then you should use an Excel file instead. You'll see this if you ever edit a CSV in excel manually and go to save it as a CSV again it will warn you that your formatting will be lost.

EDIT

I happened to stumble across a great CSV reading and writing library that has a very simple API and good documentation.

Related