0

I am building an application in Visual Studio 2019 Community edition to convert an Excel XLS file to a CSV. I had found some example code that was using the ExcelReader library and modified it so it would pull the XLS file and make a test.csv file. When I run this I do not get any errors back, but the file is not created.

This is to help automate a currently manual process where we have to manually open the XLS file and save it as a CSV. I am using Visual Studio Community edition (2019) and have added the ExcelReader library.

'''public partial class Default2 : System.Web.UI.Page
{
    static void Main() { }
    DataSet result = new DataSet();
    string filePath = 
@"C:\Users\BEM26331\Documents\AppDevProjects\9.10.19.xls";

    protected void UploadButton_Click(object sender, EventArgs e)
    {
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        FileStream stream = File.Open(filePath, FileMode.Open, 
FileAccess.Read);

        Excel.IExcelDataReader excelReader = 
Excel.ExcelReaderFactory.CreateBinaryReader(stream);
        DataSet result = excelReader.AsDataSet();
        excelReader.Close();

        result.Tables[0].TableName.ToString();

        string csvData = "";
        int row_no = 0;
        int ind = 0;

        while (row_no < result.Tables[ind].Rows.Count)
        {
            for (int i = 0; i < result.Tables[ind].Columns.Count; i++)
            {
                csvData += result.Tables[ind].Rows[row_no][i].ToString() 
+ ",";
            }
            row_no++;
            csvData += "\n";
        }

        string output = 
@"C:\Users\BEM26331\Documents\AppDevProjects\test.csv";
        StreamWriter csv = new StreamWriter(@output, false);
        csv.Write(csvData);
        csv.Close();
    }
}'''

The end result should create the same file, but saved as a CSV. The actual output does not create any file.

1 Answer 1

1

Something like this perhaps?:

    public void ConvertToCSV(string sourceFile, string targetFile)
            {
                using (var stream = System.IO.File.Open(sourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read))
                {
                    //add ExcelDataReader and ExcelDataReader.DataSet
                    //Reading from a OpenXml Excel file (2007 format; *.xlsx)
                    using (var reader = ExcelDataReader.ExcelReaderFactory.CreateOpenXmlReader(stream))
                    {
                        //DataSet result = reader.AsDataSet();
                        DataSet result = reader.AsDataSet(new ExcelDataSetConfiguration()
                        {
                            ConfigureDataTable = (_) => new ExcelDataTableConfiguration() { UseHeaderRow = true }
                        });
                        if (result.Tables.Count > 0)
                        {
                                System.Text.StringBuilder output = new StringBuilder();
                            DataTable table = result.Tables[0];
                            //save column names
                            output.AppendLine(String.Join(",", table.Columns.Cast<System.Data.DataColumn>().ToList()));
                            //save all rows
                            foreach (System.Data.DataRow dr in table.Rows)
                            {
                                output.AppendLine(String.Join(",", dr.ItemArray.Select(f=>f.ToString() ).ToList()   ) );
                            }
                            System.IO.File.WriteAllText(targetFile, output.ToString());
                        }
                    }
                }
            }
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks! I will test this and let you know.
Sorry, do you recommend using this in place of the code I had posted, or would this be added to it?
@htmlbran86 - is it working for you as expected? then, yes, you can just re-use it.
I'm still having issues with this. I've tried using both sets of code, then just yours and getting errors. I do appreciate the help. I'll be able to look at this more tonight.
@htmlbran86 - what are the errors?, what are you using - webforms, winforms?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.