C# 上传Excel导入数据 SqlBulkCopy

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:43   1104   0

//获取后缀名
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();

// 指定上传路径
String filePath = Server.MapPath("../Upload/");
string fileName = string.Empty;

if (FileUpload1.HasFile && CheckFileType(fileExtension))
{
try
{
fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + fileExtension;

// 存在服务器指定目录下
FileUpload1.PostedFile.SaveAs(filePath + fileName);
}
catch (Exception error)
{
MessageBox.Show(error.Message.ToString());
return;
}
}
else
{
MessageBox.Show("上传失败,提示: 上传文件不能为空 或者 文件格式不正确 ");
return;
}

#region 将Excel数据导入DB

//注意,此处使用的Sheet1名称
TransferData(filePath, fileName, "Sheet1", GISSDefinition.LocalConnectionString);

#endregion

private bool CheckFileType(string fileExtension)
{
Boolean fileOK = false;

if (fileExtension.ToLower().Trim() == ".xls" || fileExtension.ToLower().Trim() == ".xlsx")
{
fileOK = true;
}

return fileOK;
}

DataSet ds = new DataSet();

// 获取全部数据
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0; " + " Data Source= " + filePath + fileName + " ; " + " Extended Properties=Excel 8.0; ";

OleDbConnection oleConn = new OleDbConnection(strConn);
oleConn.Open();

string strExcel = string.Format("select * from [{0}$] ", sheetName);

OleDbDataAdapter myda = new OleDbDataAdapter(strExcel, strConn);
myda.Fill(ds);

// 用bcp导入数据
using (SqlBulkCopy bcp = new SqlBulkCopy(connectionString))
{
bcp.DestinationTableName = "Temp_VirLog"; // 目标表
bcp.BatchSize = 100; // 每次传输的行数

bcp.WriteToServer(ds.Tables[0]);
}

oleConn.Close();

====================================================================================================

string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + oriFileName + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter("select ITEM_NO,VND_CODE,VND_NAME,TAX,CUR,PRICE,PERCENTAGE,DT_FROM,DT_TO,SRC_CODE,REMARK from [Sheet1$] S1", conn);
da.Fill(ds);
da.Dispose();
conn.Close();
conn.Dispose();

====================================================================================================

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP