[英]Reading Excel with C#
我正在嘗試使用C#讀取Excel文件,並且不斷收到此錯誤: oledbexception cannot update. database or object is read-only
oledbexception cannot update. database or object is read-only
在行上oledbexception cannot update. database or object is read-only
。 有任何想法嗎?
string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
SqlConnection conn = new SqlConnection(connStr);
//file upload path
string path = FileUpload1.PostedFile.FileName;
//Create connection string to Excel work book
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FileUpload1.PostedFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";
//Create Connection to Excel work book
OleDbConnection excelConnection = new OleDbConnection(excelConnectionString);
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Coupon], [First Name], [Last Name] from [Sheet1$]",excelConnection);
excelConnection.Open();
OleDbDataReader dReader;
dReader = cmd.ExecuteReader();
SqlBulkCopy sqlBulk = new SqlBulkCopy(conn);
//Give your Destination table name
sqlBulk.DestinationTableName = "CPC_Coupons";
sqlBulk.WriteToServer(dReader);
excelConnection.Close();
謝謝!
這是我的方法,適用於在Excel 2007中創建的工作表。
public static DataTable ReadExcel(string path)
{
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
try
{
if (!File.Exists(path))
return null;
//create the "database" connection string
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
//create the database query
string query = "SELECT * FROM [Sheet1$]" ;
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);
//fill the DataTable
dAdapter.Fill(dTable);
dAdapter.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e);
}
return dTable;
}
您需要像這樣從ConnectionStrings更改connectionstring
正如在MS Support網站上有關此ADO.net和Excel的文章
string FileName = GettheFileName;
string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+FileName+";Extended Properties="Excel 8.0;HDR=Yes;IMEX=1";
從MS支持網站ADO.net與Excel
若要解決只讀數據的此問題,請通過使用連接字符串的“擴展屬性”部分中的設置“ IMEX = 1”來啟用導入模式。 這將強制ImportMixedTypes = Text注冊表設置。
PS:如果沒有列標題,則需要在連接字符串中指定HDR = No
不要簡單地...
確保已在Excel中關閉該文檔(Excel對其具有只讀共享鎖-我認為已經有一段時間了)
如果嘗試在服務器環境中使用Interop,可能會給您帶來問題-COM權限等。
我可能還會建議使用using塊來確保執行后一切都被處置:
using(OleDbConnection excelConnection = new OleDbConnection(excelConnectionString)) {
//Create OleDbCommand to fetch data from Excel
OleDbCommand cmd = new OleDbCommand("Select [Coupon]\t[First Name]\t[Last Name] from [Sheet1$]",excelConnection);
excelConnection.Open();
...
excelConnection.Close();
}
如果這可能對您的情況有所幫助,請參見以下代碼:
public static class DatabaseManager
{
//set connection string for SQL Server Express Edition
static string connString = @"Data Source=LOCALHOST\SQLEXPRESS;Initial Catalog=DocumentStore;Integrated Security=True;Pooling=False";
//method to save document to database
public static bool SaveDocumentToDatabase(MemoryStream msDocument, DocumentType docType, string documentName)
{
//keep track of the save status
bool isSaved = false;
//create database connection
SqlConnection sqlConnection = new SqlConnection(connString);
try
{
sqlConnection.Open();
}
catch (Exception ex)
{
Settings.LogException(ex);
Console.WriteLine("Unable to open database connection");
isSaved = false;
}
string commandText = "INSERT INTO Documents (DocumentType, DocumentName, DocumentContent, CreateDate) VALUES('" + docType + "','" + documentName + "', @DocumentContent ,'" + DateTime.Now + "')";
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
sqlCommand.Parameters.AddWithValue("DocumentContent", msDocument.ToArray());
try
{
sqlCommand.ExecuteNonQuery();
Console.WriteLine("Document saved successfully");
isSaved = true;
}
catch(Exception ex)
{
Console.WriteLine("Unable to save the document to database");
Settings.LogException(ex);
isSaved = false;
}
//close database connect
sqlConnection.Close();
return isSaved;
}
public static bool LoadDocumentFromDataBase(DocumentType docType)
{
//keep track of the retrieve status
bool isRetrieved = false;
//create database connection
SqlConnection sqlConnection = new SqlConnection(connString);
try
{
sqlConnection.Open();
}
catch(Exception ex)
{
Console.WriteLine("Unable to open database connection");
Settings.LogException(ex);
isRetrieved = false;
}
string commandText = "SELECT * FROM Documents WHERE DocumentType ='" + docType + "'";
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(commandText, sqlConnection);
SqlCommand sqlCommand = new SqlCommand(commandText, sqlConnection);
DataTable dtDocuments = new DataTable();
try
{
sqlDataAdapter.Fill(dtDocuments);
Console.WriteLine("Document retrieved successfully");
isRetrieved = true;
}
catch(Exception ex)
{
Console.WriteLine("Unable to retrieve documents from database");
Settings.LogException(ex);
isRetrieved = false;
}
}
}
string fileName = @"C:\Users\janki.prashar\Desktop\k.xls";
string ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\"";
OleDbConnection con = new OleDbConnection(ConStr);
con.Open();
OleDbCommand ad = new OleDbCommand("select * from [SheetName$]", con);
OleDbDataReader dr = ad.ExecuteReader();
System.Data.DataTable dt = new System.Data.DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt;
con.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.