アイデア:エクセルSQL Serverへ - C#
- XLSを読むとMicrosoft SQLのデータをアップロードする
問題:
- のみ最初の列はにアップロードされていますDB
マイコード:
DB上private void button1_Click(object sender, EventArgs e) {
// string path = @"XXXX\xls_test\Book1.xlsx";
string path = @ "XXXX\xls_test\Book1.xlsx";
ImportDataFromExcel(path);
}
public void ImportDataFromExcel(string excelFilePath) {
//declare variables - edit these based on your particular situation
string ssqltable = "Table1";
// make sure your sheet name is correct, here sheet name is sheet1, so you can change your sheet name if have different
string myexceldataquery = "select student from [Sheet1$]";
try {
//create our connection strings
//string sexcelconnectionstring = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + excelFilePath + ";" + "Extended Properties=" + "\"Excel 8.0; HDR=Yes; IMEX=1;\"";
string sexcelconnectionstring = @ "Provider=Microsoft.ACE.OLEDB.12.0;Data Source= XXXX\xls_test\Book1.xlsx" + ";" + "Extended Properties=Excel 12.0";
string ssqlconnectionstring = "XXXX";
//execute a query to erase any previous data from our destination table
string sclearsql = "delete from " + ssqltable;
SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring);
SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn);
sqlconn.Open();
sqlcmd.ExecuteNonQuery();
sqlconn.Close();
//series of commands to bulk copy data from the excel file into our sql table
OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring);
OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn);
oledbconn.Open();
OleDbDataReader dr = oledbcmd.ExecuteReader();
SqlBulkCopy bulkcopy = new SqlBulkCopy(ssqlconnectionstring);
bulkcopy.DestinationTableName = ssqltable;
while (dr.Read()) {
bulkcopy.WriteToServer(dr);
}
dr.Close();
oledbconn.Close();
MessageBox.Show("File imported into sql server.");
} catch (Exception ex) {
//handle exception
MessageBox.Show(ex.ToString());
MessageBox.Show("Enter exception");
}
}
表:最後に https://drive.google.com/drive/folders/0B98UpTa2n4XbeHZtOHU2cVotUms?usp=sharing
、私が取ったから、このコードの大部分:
CREATE TABLE [dbo].[Table1](
[student] [varchar](50) NULL,
[rollno] [int] NULL,
[course] [varchar](50) NULL
) ON [PRIMARY]
GO
XLSとDBの例から、あなたのwannaアクセス2枚の画像の場合https://code.msdn.microsoft.com/office/Import-Excel-Spreadsheet-2b7ca7cf#content 少し変わったが、ほとんどのアイデアはこれらのリンクから来ている。
何か助けてください!ありがとうございました。
うわー、それは私の部分から若者だった! はい、あなたの推測が問題でした。 ありがとうございます! –