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

4

我的应用程序可以导入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

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

在IT技术方面。
4个回答

1

你的错误可能是由于 Excel 驱动程序问题引起的,但我不确定。然而,这个错误是因为你的计算机缺少一些必需的 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();

                }
            }

        }
    }

希望这对你有用。
谢谢。


0

这里有另一个stackoverflow线程,深入探讨了这些错误的类型。 使用OLEDB将数据写入Excel文件

使用旧的连接库编写的代码往往会出现这些问题。


-1

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

你写的是Excel.0,不应该是Excel X.0吗?其中X是版本号,比如8.0。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接