Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I am trying to create and application that allows you to read a Spreadsheet from excel and to then save this out to a CSV file.

This application uses a Windows form which allows the user to select the spreadsheet and allows to name the new CSV file.

I have got to the point of writing to the CSV file, however there is an issue with writing to the CSV file as the data being written isn't correct, I'm not sure what I have done wrong and any info is gratefully appreciated.

My Code:

C#
public bool OutPutFileIsValid = false;
        public string FileLocation;
        public string OutPutFile;

        public XlSconverter()
        {
            InitializeComponent();
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            ConvertSpreadsheet();
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtBxFileLocation.Text = openFileDialog1.FileName;

                FileLocation = txtBxFileLocation.Text;
            }
        }
        public void ConvertSpreadsheet()
        {
            CreateOutPutFile();
        }
        public void CreateOutPutFile()
        {
            var newFileName = txtBxNewFileName.Text + ".csv";

            if (!File.Exists(newFileName))
            {
                using (var fs = File.Create(newFileName))
                {

                    for (byte i = 0; i < 100; i++)
                    {
                        fs.WriteByte(i);
                    }

                    OutPutFileIsValid = true;

                    WriteCsv();
                }
            }
            else
            {
                OutPutFile = newFileName;
                MessageBox.Show("File Already exists", newFileName);
            }
        }

        public void WriteCsv()
        {
            var dt = new DataTable();

            OutPutFile = txtBxNewFileName.Text;

            using (var wtr = new StreamWriter(OutPutFile))

                foreach (DataRow row in dt.Rows)
                {
                    var firstLine = true;
                    foreach (DataColumn col in dt.Columns)
                    {
                        if (!firstLine)
                        {
                            wtr.Write(",");
                        }
                        else
                        {
                            firstLine = false;
                        }
                        var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");

                        wtr.Write("\"{0}\"", data);

                        wtr.WriteLine();
                    }
                }
        }
    }
}
Posted

1 solution

Hey Glen,

There are several things you could try. I tend to use the method below quite frequently :
C#
static void ConvertExcelToCSV(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
   if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
   if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

   // connection string
   var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
   var cnn = new OleDbConnection(cnnStr);

   // get schema, then data
   var dt = new DataTable();
   try {
      cnn.Open();
      var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
      if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
      string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
      string sql = String.Format("select * from [{0}]", worksheet);
      var da = new OleDbDataAdapter(sql, cnn);
      da.Fill(dt);
   }
   catch (Exception e) {
      // ???
      throw e;
   }
   finally {
      // free resources
      cnn.Close();
   }

   // write out CSV data
   using (var wtr = new StreamWriter(csvOutputFile)) {
      foreach (DataRow row in dt.Rows) {
         bool firstLine = true;
         foreach (DataColumn col in dt.Columns) {
            if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
            var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
            wtr.Write(String.Format("\"{0}\"", data));
         }
         wtr.WriteLine();
      }
   }
}

You could also checkout the .SaveAs() method in Excel object.
C#
wbWorkbook.SaveAs("c:\filename.csv", Microsoft.Office.Interop.Excel.XlXlFileFormat.xlCSV)

Or :
C#
public static void SaveAs()
{
    Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();
    Microsoft.Office.Interop.Excel.Workbook wbWorkbook = app.Workbooks.Add(Type.Missing);
    Microsoft.Office.Interop.Excel.Sheets wsSheet = wbWorkbook.Worksheets;
    Microsoft.Office.Interop.Excel.Worksheet CurSheet = (Microsoft.Office.Interop.Excel.Worksheet)wsSheet[1];
    Microsoft.Office.Interop.Excel.Range thisCell = (Microsoft.Office.Interop.Excel.Range)CurSheet.Cells[1, 1];
    thisCell.Value2 = "This is a test.";
    wbWorkbook.SaveAs(@"c:\one.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.SaveAs(@"c:\two.csv", Microsoft.Office.Interop.Excel.XlFileFormat.xlCSVWindows, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    wbWorkbook.Close(false, "", true);
}


There could be issue if you're using foreign characters, like chinese but you'd have to figure that one out by trial and error I guess. Hope this helps.
 
Share this answer
 
Comments
Glen Childs 25-Sep-13 7:29am    
Brilliant, works! Thanks ever so much for your help Rick!
Rick van Woudenberg 25-Sep-13 7:33am    
no worries. Glad I could help !
Glen Childs 26-Sep-13 4:21am    
Rik, the code for some reason has decided to throw up an error : "External table is not in the correct format". I have been researching on the Internet but haven't found a solution. The forums seem to suggest that it is the connection string for excel however the connection string and the rest of the code is the same or similar as yours above.

Any suggestions?
Rick van Woudenberg 26-Sep-13 4:25am    
Glen, which code did you use. I posted several snippits.
Glen Childs 1-Oct-13 10:36am    
Rick,

How would I be able to get your top solution to be able to convert all the sheets in the workbook?

Regards,

Glen

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900