asp上传excle文件并导入到access数据库

<%
function FSOFileDel(filename)
Dim objFSO,objCountFile,FiletempData
On Error Resume Next
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objCountFile =objFSO.DeleteFile(Server.MapPath(filename),true)
objCountFile.Close
Set objCountFile=Nothing
Set objFSO = Nothing
End Function




dim action,files
action=trim(request("action"))
files=trim(request("files"))
select case action
case "add"
call add(files)
case else
call default()
end select        
%>

<%sub default()%>
<form action="?action=add" method="post" id="form1" name="form1">
<table border="0" cellspacing="0" cellpadding="0">
<tr class="title2">
<td colspan="2">批量上传</td>
</tr>
<tr>
<td>1.上传Excle文件&nbsp;</td>
<td><input name="files" type="hidden" id="files" />
<iframe frameborder="0" scrolling="no" height="25" width="400" src="upload.asp?action=add"></iframe>&nbsp;</td>
</tr>
<tr>
<td>2.点击"开始上传"&nbsp;</td>
<td>  <label>
<input type="submit" name="button" id="button" value="开始上传" />
</label>&nbsp;</td>
</tr>
</table>



</form>
<%end sub%>
<%
sub add(files)
dim FileName

if files="" then ClientAlert"请先上传Excle文件","?"

FileName="../upload/file/"&files  '取得文件路径
Dim connEX
set connEX=CreateObject("ADODB.connection")
connEX.Open "Driver={Microsoft Excel Driver (*.xls)};" & _
"DriverId=790;" & _
"Dbq=" & server.mappath(""&FileName&"") & ";" & _
"DefaultDir=G:/"

set rs=createobject("ADODB.recordset")
rs.Open "Select * From [Sheet1$]",connEX, 2, 2
if rs.eof then
response.write "Excel表中无纪录"
else
'  set connDB = Server.CreateObject("ADODB.Connection")
'  DBPath = Server.MapPath("excel.mdb")
'  'RESPONSE.WRITE DBpath
'  connDB.Open "driver={Microsoft Access Driver (*.mdb)};dbq=" & DBPath
Set RsDB = Server.CreateObject("ADODB.Recordset")
SqlDB="Select * from product"
RsDB.open sqlDB,conn,1,3
do while not  rs.eof '利用循环读出数据
RsDB.addnew
RsDB("ProName")=rs(0)
RsDB("ProClassId")=rs(1)
RsDB("ProPics")=rs(2)
RsDB("ProPic")=rs(3)
RsDB("ProFeaturesCn")=rs(4)
RsDB("IsNew")=rs(5)
RsDB("IsHot")=rs(6)
RsDB("Taxis")=rs(7)
Rs.update
RsDB.movenext
rs.movenext
loop
'response.redirect FileName
end if
RsDB.movefirst
if RsDB.eof then
response.write "数据库中无记录"
end if
rs.close
set rs=nothing
set connEX=nothing

Call FSOFileDel("../upload/file/"&files)'导入成功后及时删除上传文件.

ClientAlert"导入成功,点确定继续。","?"
end sub

%>

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
ASP.NET MVC导入Excel文件数据库功能可以通过以下步骤实现: 1. 创建一个控制器和视图来上Excel文件。 2. 使用第三方库如EPPlus来解析Excel文件并将其转换为数据表。 3. 使用ADO.NET连接到数据库并将数据表中的数据插入到数据库中。 以下是一个示例控制器和视图的代码: 控制器: ``` public class ExcelController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Import(HttpPostedFileBase file) { if (file != null && file.ContentLength > 0) { string fileName = Path.GetFileName(file.FileName); string fileExtension = Path.GetExtension(fileName); if (fileExtension == ".xls" || fileExtension == ".xlsx") { string filePath = Server.MapPath("~/Content/" + fileName); file.SaveAs(filePath); DataTable dt = ReadExcelFile(filePath); InsertDataIntoDatabase(dt); return RedirectToAction("Index"); } else { ViewBag.Message = "Please upload a valid Excel file."; return View("Index"); } } else { ViewBag.Message = "Please select an Excel file to upload."; return View("Index"); } } private DataTable ReadExcelFile(string filePath) { using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; DataTable dt = new DataTable(); bool hasHeaderRow = true; foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column]) { dt.Columns.Add(hasHeaderRow ? firstRowCell.Text : string.Format("Column {0}", firstRowCell.Start.Column)); } int startRow = hasHeaderRow ? 2 : 1; for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++) { var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column]; DataRow row = dt.Rows.Add(); foreach (var cell in wsRow) { row[cell.Start.Column - 1] = cell.Text; } } return dt; } } private void InsertDataIntoDatabase(DataTable dt) { string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = connection.CreateCommand(); command.CommandType = CommandType.Text; command.CommandText = "INSERT INTO MyTable (Column1, Column2, Column3) VALUES (@Column1, @Column2, @Column3)"; foreach (DataRow row in dt.Rows) { command.Parameters.AddWithValue("@Column1", row["Column1"]); command.Parameters.AddWithValue("@Column2", row["Column2"]); command.Parameters.AddWithValue("@Column3", row["Column3"]); command.ExecuteNonQuery(); command.Parameters.Clear(); } } } } ``` 视图: ``` @{ ViewBag.Title = "Import Excel File"; } <h2>Import Excel File</h2> @using (Html.BeginForm("Import", "Excel", FormMethod.Post, new { enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() <div class="form-group"> <label for="file">Select Excel File:</label> <input type="file" name="file" id="file" /> </div> <button type="submit" class="btn btn-primary">Import</button> <div class="alert alert-danger" role="alert">@ViewBag.Message</div> } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值