[英]C# Excel Connection
你好,我需要連接到excel文件以更新列,我有此代碼
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
namespace Excel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand();
string sql = null;
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\farm.xls';Extended Properties=Excel 8.0;");
MyConnection.Open();
myCommand.Connection = MyConnection;
sql = "Update [Sheet1$] set name = 'FARM GDL' where COMERCIO like 'FARM GUADALAJARA'";
myCommand.CommandText = sql;
myCommand.ExecuteNonQuery();
MyConnection.Close();
MessageBox.Show("Success");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
但是有些東西不起作用,當我運行它打開連接
我可以??? 請,謝謝!
上面的連接字符串中發現了一些錯誤:
以這種方式更改連接字符串:
MyConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\farm.xls';'Extended Properties=Excel 8.0;HDR=YES'");
如果您的Excel文件的第一行沒有標題,則整個查詢都會更改,因為您不能使用name
和COMERCIO
作為列名稱。 相反,您需要使用字母F和后跟的列號(如set F1 = 'FARM GDL' where F2 like '...'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.