导出Excel表格数据为csv格式

本文关键字:csv 格式 数据 Excel 表格 导出 | 更新日期: 2023-09-27 18:02:29

在我的应用程序中,我可以导入csv文件,但我有excel表中的数据,所以我需要将其转换为csv格式。我从net中获得了用于将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

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

导出Excel表格数据为csv格式

您的错误可能是由于excel驱动程序问题引起的,我不是100%确定,但是由于一些所需的dll缺失而导致的错误。

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

如果它没有解决,你可以使用下面粘贴的代码,这是我写的,只是为了回答你的问题,但首先我应该告诉你,下面的代码部分是不有效的,如果转换文件有相当多的记录的ex65000

要使用下面的代码部分,您需要在下面添加引用

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();
                }
            }
        }
    }

希望这对你有用

谢谢。

读取此线程system . data . oledb . oledbeexception: Could not find installable ISAM

下面是另一个stackoverflow线程,它对这类错误进行了一些深入的研究。用OLEDB写入excel文件

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

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

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