• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 444
  • Last Modified:

How to write out worksheet file names as CSV type files from a workbook in C# using VS2010 ?

I am working on a C# web application using VS2010.

I call a method to try and convert 4 particular worksheets within each workbook I process
into CSV type files.

Do you know how I can correct my error?

I seem to have no problem converting the first worksheet into a CSV file.
The file comes out as "105 Internal  08-28-2013_Bank Credits (A).csv".

I want to name the ouput CSV file as the combination of 4 components:
1) the workbook name (without the .XLS, followed by
2) an underscore
3) followed by the worksheet name
4) followed by .CSV (the file type)

However, it seems that after I convert this first worksheet, that I am accidentally
changing the workbook name through my assignment variables.

After I read the worksheet named "Bank Credits (A)", it seem I mess up the name of the following worksheets.

The 2nd worksheet comes out as concatenation of the 1st and 2nd worksheet names:

105 Internal  08-28-2013_Bank Credits (A)_Bank Debits (B).csv

My code is in the attached file.
1 Solution
That is weird, I must admit it: while doing worksheet.SaveAs it changes also the name of the workbook.

However, you can do it like this (change the try finally inside the ConvertExcelToCsv method):

                Workbook workbook = xl.Workbooks.Open(source);
                wbname = workbook.Name;
                wbnameroot = wbname.Substring(0, wbname.IndexOf("."));

                for (int k = 1; k <= workbook.Worksheets.Count; k++)
                    Worksheet ws = (Worksheet)workbook.Sheets[k];
                    if (ws.Name == "Bank Credits (A)" || ws.Name == "Bank Debits (B)" || ws.Name == "Book Debits (C)" || ws.Name == "Book Credits (D)")
                        String cDestFile = destination + wbnameroot + "_" + ws.Name + ".csv";
                        ws.SaveAs(cDestFile, XlFileFormat.xlCSV);
                xl.DisplayAlerts = false;

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now