将Excel工作表数据导出为csv格式

时间:2011-07-16 04:25:35

标签: c# csv export

在我的应用程序中,我可以导入csv文件,但我有excel表中的数据,所以我需要将其转换为csv格式。 我从网上获取代码,用于将excel数据导出到csv,当我下载它的zip文件并运行它的工作但是当我将此程序复制到vs 2008并运行它时它无效

代码是

using System;
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Collections.Generic;
using System.Text;

namespace XlsToCsv
{
    class Program
    {
        static void Main(string[] args)
        {
            string sourceFile, worksheetName, targetFile;
            sourceFile = @"D:\emp.xls";worksheetName = "sheet1"; targetFile = @"D:\empcsv.csv";
            convertExcelToCSV(sourceFile, worksheetName, targetFile);
        }

        static void convertExcelToCSV(string sourceFile, string worksheetName, string targetFile)
        {
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sourceFile + ";Extended Properties=\" Excel.0;HDR=Yes;IMEX=1\""; 
            OleDbConnection conn = null;
            StreamWriter wrtr = null;
            OleDbCommand cmd = null;
            OleDbDataAdapter da = null; 
            try
            {
                conn = new OleDbConnection(strConn);
                conn.Open();

                cmd = new OleDbCommand("SELECT * FROM [" + worksheetName + "$]", conn);
                cmd.CommandType = CommandType.Text;
                wrtr = new StreamWriter(targetFile);

                da = new OleDbDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);

                for (int x = 0; x < dt.Rows.Count; x++)
                {
                    string rowString = "";
                    for (int y = 0; y < dt.Columns.Count; y++)
                    {
                        rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
                    }
                    wrtr.WriteLine(rowString);
                }
                Console.WriteLine();
                Console.WriteLine("Done! Your " + sourceFile + " has been converted into " + targetFile + ".");
                Console.WriteLine();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.ToString());
                Console.ReadLine();
            }
            finally
            {
                if (conn.State == ConnectionState.Open)
                    conn.Close();
                conn.Dispose();
                cmd.Dispose();
                da.Dispose();
                wrtr.Close();
                wrtr.Dispose();
            }
        }
    }
}

像这样抛出错误

System.Data.OleDb.OleDbException: Could not find installable ISAM.

   at System.Data.OleDb.OleDbConnectionInternal..ctor(OleDbConnectionString cons
tr, OleDbConnection connection)

   at System.Data.OleDb.OleDbConnectionFactory.CreateConnection(DbConnectionOpti
ons options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection o
wningObject)

   at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbC
onnection owningConnection, DbConnectionPoolGroup poolGroup)

   at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection ow
ningConnection)

   at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection ou
terConnection, DbConnectionFactory connectionFactory)

   at System.Data.OleDb.OleDbConnection.Open()

   at Excel_To_csv.Program.convertExcelToCSV(String sourceFile, String worksheet
Name, String targetFile) in D:\Excel to csv\Excel To csv\Excel To csv\Program.cs
:line 41

为什么会出现这个错误我不知道

4 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

您的错误可能是由于excel驱动程序问题而产生的,我不是100%确定,但是由于某些必需的dll而导致的错误从您的计算机中丢失。

您可以通过将MDAC安装到您的计算机并尝试执行此操作来解决此问题。

如果它没有解决,你可以使用我写的下面粘贴的代码作为你的问题的答案,但首先我应该告诉你,如果转换文件有相当多的记录的前65000

要使用以下代码部分,您需要添加以下参考

using Excel = Microsoft.Office.Interop.Excel;
using Office = Microsoft.Office.Core;

功能

 private void EXCELTOCSV()
    {
        OpenFileDialog excelSheetToOpen = new OpenFileDialog();
        excelSheetToOpen.Filter = "Excel 97- 2003 WorkBook (*.xls)| *.xls | Excel 2007 WorkBook (*.xlsx) | *.xlsx | All files (*.*)|*.*";
        excelSheetToOpen.FilterIndex = 3;
        excelSheetToOpen.Multiselect = false;



        if (excelSheetToOpen.ShowDialog() == DialogResult.OK)
        {

            Excel.Application excelApp = new Excel.Application();
            String workbookPath = excelSheetToOpen.FileName;
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(workbookPath);
            Excel.Sheets excelWorkBookSheets = excelWorkbook.Sheets;

            Excel.Range _UsedRangeOftheWorkSheet;


            foreach (Excel.Worksheet _Sheet in excelWorkBookSheets)
            {
                if (_Sheet.Name =="ExcelSheetName")
                {

                    _UsedRangeOftheWorkSheet = _Sheet.UsedRange;

                    Object[,] s = _UsedRangeOftheWorkSheet.Value;

                    System.IO.StreamWriter sw = new System.IO.StreamWriter("FileName.csv", true);

                    for (int b = 0; b < s.Length; b++)
                    {
                        StringBuilder sb = new StringBuilder();
                        for (int c = 0; c < s.Rank; c++)
                        {
                            if (sb == null)
                            {
                                sb.Append((String)s[b, c]);
                            }
                            else
                            {
                                sb.Append("," + (String)s[b, c]);
                            }
                        }
                        sw.WriteLine(sb.ToString());
                    }
                    sw.Close();

                }
            }

        }
    }

希望这对你有用

感谢。

答案 2 :(得分:0)

这是另一个stackoverflow线程,它深入研究了这些类型的错误。 Writing into excel file with OLEDB

使用这些旧连接库的代码往往存在这些问题。

答案 3 :(得分:-1)

看起来您的问题出现在连接字符串中的扩展属性中。

您写的Excel.0不应该是Excel X.0,其中X是版本号。类似于8.0