简体   繁体   English

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

[英]Export Excel sheet data to csv format

In my application i can import csv file but i have data in excel sheet so i need to convert it to csv format.在我的应用程序中,我可以导入 csv 文件,但我在 excel 表中有数据,所以我需要将其转换为 csv 格式。 i got code from net for exporting excel data to csv when i downloaded zip file of it and run that its working but its not working when i copy this program to vs 2008 and run it当我下载它的 zip 文件并运行它的工作但它不工作当我将此程序复制到 vs 2008

The code is代码是

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

its throwing error like this它的抛出错误是这样的

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

why is this error coming i dont know为什么会出现这个错误,我不知道

your error may be arising because of excel driver issues im not 100% sure about that however this error arising because of some required dll's are missing form you computer.您的错误可能是由于 excel 驱动程序问题而引起的,我不能 100% 确定这一点,但是由于您的计算机缺少某些必需的 dll 而出现此错误。

you might be able to solve this issue by installing MDAC to your computer and try to execute this.您可以通过将 MDAC 安装到您的计算机并尝试执行此操作来解决此问题。

if it's not solved you can use the below pasted code which is written by me just as a answer to your question but first of all i should tell you this below code part is not efficient if the conversion file has quite considerable number of record's ex 65000如果没有解决,您可以使用我编写的以下粘贴代码作为您问题的答案,但首先我应该告诉您,如果转换文件有相当多的记录前 65000,则下面的代码部分效率不高

To use the below code part you need to add below reference要使用以下代码部分,您需要添加以下参考

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

Function Function

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

                }
            }

        }
    }

Hope this will work for you希望这对你有用

Thanks.谢谢。

Here is another stackoverflow thread that goes into some depth on these sorts of errors.这是另一个 stackoverflow 线程,它对这些类型的错误进行了深入探讨。 Writing into excel file with OLEDB 使用 OLEDB 写入 excel 文件

Code that uses those older connection libraries tends to have these sorts of problems.使用那些较旧的连接库的代码往往会出现这类问题。

Looks like you problem is in Extended Properties in the Connection String.看起来您的问题出在连接字符串的扩展属性中。

You have written Excel.0 shouldn't it be Excel X.0 where X is the version number.Like 8.0你已经写Excel.0不应该是Excel X.0其中X是版本号。就像 8.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM