Mình đưa dữ liệu dạng file excel lên host iis để tiến hành thao tác trên file đó
và đây là code
Mã:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
namespace LT_Mang
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btImport_Click(object sender, EventArgs e)
{
//Chuỗi kiểm tra dữ liệu có phải là file excel không
string excelContentType = "application/vnd.ms-excel";
string excel2007ContentType = "application/vnd.openxmlfomats-officedocument.spreadsheetml.sheet";
if (!FileUpload1.HasFile)
{
lbThongbao.Text = "Vui lòng chọn file cần Upload";
}
else
{
try
{
//Kiểm tra điều kiện file upload có phải là file excel hay không
if (FileUpload1.PostedFile.ContentType != excelContentType && FileUpload1.PostedFile.ContentType != excel2007ContentType)
{
lbThongbao.Text = "Vui lòng chọn tập file excel";
}
else
{
//Post file lên thư mục tạm (Temp)
string path = string.Concat(Server.MapPath("~/Temp/" + FileUpload1.FileName));
FileUpload1.SaveAs(path);
//Sau khi upload xong đọc dữ liệu từ file này
//code này là lấy đường dẫn của file excel bỏ vào connection string
string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties =Excel 8.0", path);
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = excelConnectionString;
OleDbCommand comand = new OleDbCommand("Select*from [Sheet1$]", connection);
connection.Open();
DbDataReader dr = comand.ExecuteReader();
//Sau khi lấy dữ liệu vào dr Insert vào trong SQL server
//Lấy chuỗi kết nối tới sql server database là DBImportDaTaFromExcel
string sqlConnectionString = @"Data Source=JACKIE-PC\SQLEXPRESS;Initial Catalog=DBImportDaTaFromExcel;Integrated Security=True";
SqlBulkCopy bulkInsert = new SqlBulkCopy(sqlConnectionString);
bulkInsert.DestinationTableName = "DuLieu"; //Tên bảng muốn chèn dữ liệu vào
bulkInsert.WriteToServer(dr);
lbThongbao.Text = "Thành công";
}
}
catch
{
lbThongbao.Text = "Lỗi xảy ra trong quá trình import";
}
}
}
}
}
Mình chạy sửa hoài không được toàn bị lỗi "Lỗi xảy ra trong quá trình import";
Nản quá
Help me[IMG]images/smilies/wings_cry.gif[/IMG][IMG]images/smilies/wings_cry.gif[/IMG][IMG]images/smilies/wings_cry.gif[/IMG][IMG]images/smilies/wings_cry.gif[/IMG][IMG]images/smilies/wings_cry.gif[/IMG]
View more random threads:
Sự đa dạng trong các mẫu mã và kiểu dáng của sản phẩm Đồ Thờ Gỗ cũng là điểm thu hút đặc biệt. Từ những tượng phật nhỏ xinh, đến các bức thư pháp hoặc các bát hương gỗ được điêu khắc tỉ mỉ, đều mang...
Tinh Thần Truyền Bá: Skyhome.vn và...