使用c#将CSV连接添加到Excel

时间:2014-05-23 18:09:39

标签: c# excel csv

我尝试了很多方法,我想用c#添加csv连接到excel 我尝试过的事情:

string textpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string path = textpath + "\\filename.csv"

string csvconectionstring = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + textpath + ";Extensions=asc,csv,tab,txt;";
                    SaturnAddIn.getInstance().Application.ActiveWorkbook.Connections.Add2("csv", csvconectionstring,null, 6, true, false);

string csvconectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"text;HDR=Yes;FMT=Delimited";
                    SaturnAddIn.getInstance().Application.ActiveWorkbook.Connections.Add2("csv", csvconectionstring,null, 6, true, false); 

这是我得到的例外

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
  Source=""
  StackTrace:
       at System.RuntimeType.ForwardCallToInvokeMember(String memberName, BindingFlags flags, Object target, Int32[] aWrapperTypes, MessageData& msgData)
       at Microsoft.Office.Interop.Excel.Connections.Add2(String Name, String Description, Object ConnectionString, Object CommandText, Object lCmdtype, Object CreateModelConnection, Object ImportRelationships)
       at Saturn.DataImportForm.CouchImport() in c:\Users\dtaylor\Documents\Visual Studio 2013\Projects\Saturn\Saturn\Saturn\CouchImport.cs:line 43
       at Saturn.DataImportForm.ImportButton_Click(Object sender, EventArgs e) in c:\Users\dtaylor\Documents\Visual Studio 2013\Projects\Saturn\Saturn\Saturn\DataImportForm.cs:line 41
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
  InnerException: 

1 个答案:

答案 0 :(得分:1)

Microsoft Jet OLE DB 4.0 TextFile连接字符串 TextFile Connect Strings

如果要查看DataSet中的数据

string strFileName = textpath + "\\filename.csv";
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) +"; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM " + System.IO.Path.GetFileName(strFileName), conn);
DataSet ds = new DataSet("Temp");
adapter.Fill(ds);
DataTable tb = ds.Tables[0];