[英]Importing Excel sheet into SQL Server with C#
我正在编写一个简单的程序,将excel工作表导入数据库,但是遇到以下错误:
找不到可安装的ISAM
我不确定这意味着什么,经过数小时的搜索,我转向了SO。 有很多关于Jet和ACE的讨论,我不确定有什么区别,但是这里有一个摘要:我有一个称为test或test1的excel文件,我只想导入文件中的第一张表。 到目前为止,这是我的源代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
string filePath = null;
public Form1()
{
InitializeComponent();
}
//Method to check database connection
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn;
connetionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=SSPI;";
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
//Method to select a file
private void button2_Click(object sender, EventArgs e)
{
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=Excel 12.0,HDR=Yes;IMEX=1";
// Create Connection to Excel Workbook
using (OleDbConnection connection =
new OleDbConnection(excelConnectionString))
{
OleDbCommand command = new OleDbCommand
("Select * FROM [Sheet1$]", connection);
connection.Open(); //HERE IS WHERE THE ERROR IS
// Create DbDataReader to Data Worksheet
using (DbDataReader dr = command.ExecuteReader())
{
// SQL Server Connection String
string sqlConnectionString = "Data Source=Zach-PC;Initial Catalog=master;Integrated Security=True";
// Bulk Copy to SQL Server
using (SqlBulkCopy bulkCopy =
new SqlBulkCopy(sqlConnectionString))
{
bulkCopy.DestinationTableName = "Table";
bulkCopy.WriteToServer(dr);
MessageBox.Show("Data Exoprted To Sql Server Succefully");
}
}
}
}
}
}
我在正确的庄园里来吗?
您需要将连接字符串的Extended Properties
部分用引号引起来:
// here and here
// --> v v
string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Users/Zach/Documents/test1.xls;Extended Properties=""Excel 12.0,HDR=Yes;IMEX=1""";
您的计算机上可能未安装Office oledb驱动程序。 您应该从Microsoft网站下载它。 安装后,您的代码应运行。
如果您正在阅读Office 2007(或更高版本)的excel文件,那么我建议您使用开放源代码库Epplus来读取excel文件。它纯粹是.NET库,因此您不会依赖oledb驱动程序。
EPPlus是一个.net库,它使用Open Office Xml格式(xlsx)读取和写入Excel 2007/2010文件。
您可以使用此库轻松地将excel文件读入数据表。 看看这个线程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.