private void btnSelectFile_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog1 = new OpenFileDialog();
openfiledialog1.ShowDialog();
openfiledialog1.Filter = "allfiles|*.xlsx";
openfiledialog1.Filter = "allfiles|*.xlsm";
txtfilepath.Text = openfiledialog1.FileName;
}
private void btnUpload_Click(object sender, EventArgs e)
{
string path = txtfilepath.Text;
string ConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";
DataTable Data = new DataTable();
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
conn.Open();
OleDbCommand cmd = new OleDbCommand(@"SELECT * FROM [Student_excel$]", conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(Data);
conn.Close();
}
string ConnStr = MyConString;
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(ConnStr))
{
bulkCopy.DestinationTableName = "dbo.Student_excel";
bulkCopy.ColumnMappings.Add("userid", "userid");
bulkCopy.ColumnMappings.Add("name", "name");
bulkCopy.ColumnMappings.Add("age", "age");
bulkCopy.ColumnMappings.Add("location", "location");
bulkCopy.WriteToServer(Data);
MessageBox.Show("UPLOAD SUCCESSFULLY");
}
}
当我将一些Excel文件(ExcelBook1.xlsx)导入windowsFormApplication时,Visual Studio会给我一些错误:
'Student_excel $'不是有效名称。确保它不包含无效字符或标点符号,并且不会太长。