1

我正在尝试在 C# 中将 excel 文件导入 SQL Server 2005,但出现错误。

这是我的代码:

namespace excel
{
public partial class Csharp_Excel : Form
{
    public Csharp_Excel()
    {
        InitializeComponent();
    }

    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter();

    DataTable dt = new DataTable();

    private void button1_Click(object sender, EventArgs e)
    {
        string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        path = Path.Combine(path, "csharp-Excel.xls");

        string connStr = @"Server=.\\SQLEXPRESS;Data Source= C:\\Users\\adil pc\\Documents\\Visual Studio 2008\\Projects\\excel\\excel\\bin\\Debug\\csharp-Excel.xls;Initial Catalog=RMS;Integrated Security=SSPI;";

        SqlConnection con = new SqlConnection(connStr);
        string strCmd = "select * from [sheet1$A1:E7]";

        SqlCommand cmd = new SqlCommand(strCmd, con);

        try
        {
           con.Open();
            ds.Clear();
            da.SelectCommand = cmd;
            da.Fill(dt);
            dataGridView1.DataSource = ds.Tables[0];
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        finally
        {             
        }
    }

    private void btnsend_Click(object sender, EventArgs e)
    {
    }
}

我得到的错误是:

System.Data.SqlClient.SqlException:建立与 SQL Server 的连接时发生与网络相关或实例指定的错误

4

1 回答 1

0

我想我让它工作了我对连接字符串进行了一些更改:

string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\\csharp-Excel.xls;Extended Properties=\"Excel 8.0;HDR=Yes;\";

一旦我更新,它正在演示尚未在实际项目中实施。

于 2013-08-03T07:38:04.397 回答