未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。(C# EXCEL导入demo)
1. 安装office包
https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=13255
2.需要在相应的IIS应用程序池启用32位应用程序
3.代码
//前台
<script language="javascript">
$(document).ready(function () {
$('#ImportExcel').on('click', function (e) {
console.log($(this).next().attr("data-id"));
$(this).next().trigger('click'); })
})
function Upload(obj) {
var file = obj.files[0];
var formData = new FormData();
formData.append('imgFile', file);
formData.append('type', "carCheckUpload");
$.ajax({
url: "/ajax/ajax_caruseexport.ashx",
type: "post",
data: formData,
contentType: false,
processData: false,
mimeType: "multipart/form-data",
success: function (data) {
var jsondata = $.parseJSON(data);
console.log(jsondata);
alert('导入成功');
window.location.reload();
},
error: function (data) {
alert("上传失败");
}
});
}
</script> <div class="lf">
<div class="div1" style="margin-left: 15px;">
<a href="/Upload/公车检查台账导入表.xls">模板下载</a>
</div>
<div class="div1" style="margin-left: 15px;">
<a id="ImportExcel">公车检查台账导入</a>
<input style="display: none;" type="file" onchange="Upload(this)" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
</div> </div>
//后台处理程序
<%@ WebHandler Language="C#" Class="ajax_caruseexport" %> using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.OleDb;
using System.Data.Linq.SqlClient;
using System.Linq; public class ajax_caruseexport : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
private HttpContext context;
BaseService bs = new BaseService(); public void ProcessRequest(HttpContext context)
{
this.context = context;
int maxSize = 1000000000;
String savePath = "/Upload/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("yyyyMM") + "/"; Hashtable extTable = new Hashtable();
extTable.Add("file", "doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar,gz,bz2");
HttpPostedFile imgFile = context.Request.Files["imgFile"]; if (imgFile == null) showError("请选择文件。");
String dirName = context.Request.QueryString["dir"];
if (String.IsNullOrEmpty(dirName)) dirName = "file";
if (!extTable.ContainsKey(dirName)) showError("目录名不正确。");
String fileName = imgFile.FileName;
String fileExt = Path.GetExtension(fileName).ToLower(); if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) showError("上传文件大小超过限制。");
if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。"); if (!Directory.Exists(context.Server.MapPath(savePath))) Directory.CreateDirectory(context.Server.MapPath(savePath)); String newFileName = "meeting_" + DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
String fileUrl = savePath + newFileName; imgFile.SaveAs(context.Server.MapPath(fileUrl));
if (!(IsAllowedExtension(fileUrl))) showError("非法文件!请上传正确的文件!");
var msg = ImportUser(context, context.Server.MapPath(fileUrl)); Hashtable hash = new Hashtable();
hash["error"] = 0;
hash["url"] = fileUrl;
hash["msg"] = msg;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
} private void showError(string message)
{
Hashtable hash = new Hashtable();
hash["error"] = 1;
hash["message"] = message;
context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
context.Response.Write(JsonMapper.ToJson(hash));
context.Response.End();
} //文件真实性判断
private bool IsAllowedExtension(string FileUrl)
{
System.IO.FileStream fs = new System.IO.FileStream(context.Server.MapPath(FileUrl), System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
string fileclass = "";
byte buffer;
buffer = r.ReadByte();
fileclass = buffer.ToString();
buffer = r.ReadByte();
fileclass += buffer.ToString();
r.Close();
fs.Close();
/* 文件扩展名说明
*7173 gif
*255216 jpg
*13780 png
*6677 bmp
*/
Dictionary<String, String> ftype = new Dictionary<string, string>();
//添加允许的文件类型
ftype.Add("7173", "gif");
ftype.Add("255216", "jpg");
ftype.Add("13780", "png");
ftype.Add("6677", "bmp");
ftype.Add("8297", "rar");
ftype.Add("208207", "doc"); ftype.Add("3780", "pdf");
ftype.Add("8075", "xlsx"); if (ftype.ContainsKey(fileclass))
{
return true;
}
else
{
System.IO.File.Delete(context.Server.MapPath(FileUrl));
return false;
} } /// <summary>
/// 导入通讯录
/// </summary>
/// <param name="context"></param>
/// <param name="filePath"></param>
/// <returns></returns>
public string ImportUser(HttpContext context, string filePath)
{
var result = "";
string type = context.Request["type"];
if (type == "carCheckUpload")
{
DataTable dt = ExcelToDataTable(filePath);
BaseHelper.WriteLogs("ImportCarCheck", Newtonsoft.Json.JsonConvert.SerializeObject(dt) + "--" + dt.Rows.Count, "Import");
if (dt.Rows.Count > 3)
{
var firstRow = dt.Rows[1]; //第一行是检查人数据
DateTime nowTime = DateTime.Now;
for (int i = 3; i < dt.Rows.Count; i++)
{
CarUseCheckRegistration entity = new CarUseCheckRegistration()
{
carName = dt.Rows[i][0].ToString(),
brand = dt.Rows[i][1].ToString(),
linkMan = dt.Rows[i][2].ToString(),
linkTel = dt.Rows[i][3].ToString(),
company = dt.Rows[i][4].ToString(),
terminal = dt.Rows[i][5].ToString(),
endTime = dt.Rows[i][6].ToString(),
isUsually = dt.Rows[i][7].ToString(),
isRegularPark = dt.Rows[i][8].ToString(),
remark = dt.Rows[i][9].ToString(),
status = 1,
createtime = nowTime,
};
//保存
BLL_PublicCar.SaveCarUseCheckRegistration(entity);
} ImageInfo imageInfo = new ImageInfo()
{
ClassId = 520,
Title = firstRow[3] + "",
Content = firstRow[1] + "",
};
using (SiteCmsDataContext db = new SiteCmsDataContext())
{
var temp = db.ImageInfo.Where(w => w.ClassId == imageInfo.ClassId).FirstOrDefault();
if (temp == null)
{
db.ImageInfo.InsertOnSubmit(imageInfo);
db.SubmitChanges();
}
else
{
if (imageInfo.Title.IsNotNullOrEmpty())
{
temp.Title = imageInfo.Title;
}
if (imageInfo.Content.IsNotNullOrEmpty())
{
temp.Content = imageInfo.Title;
}
temp.ClassId = imageInfo.ClassId;
db.SubmitChanges();
}
}
}
}
return result;
} public DataTable ExcelToDataTable(string strExcelFileName)
{
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + GetExcelFirstTableName(strExcelFileName) + "]", strConn);
adapter.Fill(ds);
conn.Close();
return ds.Tables[0];
} public string GetExcelFirstTableName(string excelFileName)
{
string tableName = null;
if (File.Exists(excelFileName))
{
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=\"Excel 8.0\";Data Source=" + excelFileName))
{
conn.Open();
DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
tableName = dt.Rows[0][2].ToString().Trim();
}
}
return tableName;
} public bool IsReusable
{
get
{
return false;
}
}
}
未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。(C# EXCEL导入demo)的更多相关文章
- .NET读取Excel数据,提示错误:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序
解决.NET读取Excel数据时,提示错误:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序的操作: 1. 检查本机是否安装Office Access,如果未安装去去h ...
- 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序
这种错误的可能性有几种,比如: 1.没有安装数据访问组件,需要安装相应版本的数据访问组件: 2.没有安装相应版本的Office客户端,需要安装相应版本的Office客户端: 3.Microsoft.J ...
- 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序 解决方法
最近在搞asp.net.今天在做数据库操作的时候,老发生错误,还以为是自己代码有问题,检查了好久都发现错误. 错误提示: 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程 ...
- 未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序解决办法
一.未在本地计算机上注册“microsoft.ACE.oledb.4.0”提供程序 http://download.microsoft.com/download/7/0/3/703ffbcb-dc0c ...
- 未在本地计算机上注册"microsoft.ACE.oledb.12.0"提供程序解决办法
错误信息:未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序. 解决办法: 去http://download.microsoft.com/download/7/0/3/7 ...
- 未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。
笔记本装的是windows 7旗舰版64位系统,使用的是MS Office 2007(Microsoft.ACE.OLEDB.12.0,32位程序),开发用的是Visual Studio 2010,我 ...
- c#操作Excel时,抛出异常:“未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序”
我们开发环境下,使用excel导入数据到数据库中,编译的软件起初是x86 方式,起初并未发现什么问题,一切很正常: 程序该进的过程: 后来导入文件一次就要读取几百G的数据导入数据库中,使用编译的X86 ...
- 未在本地计算机上注册Microsoft.ACE.OLEDB.12.0提供程序(Oledb)
解决访问Excel数据源时出现 未在本地计算机上注册Microsoft.ACE.OLEDB.12.0提供程序1.确保安装了Microsoft.ACE.OLEDB.12.0驱动 http://downl ...
- 未在本地计算机上注册"Microsoft.ACE.OLEDB.12.0"提供程序
运行时出现了错误,提示未在本地计算机上注册"Microsoft.ACE.OLEDB.12.0"提供程序. 这个问题的原因是64位PC上安装了Office的32位版本,所以Micro ...
- 【.net】未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序解决办法
#错误描述: 在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报错: “未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序” # ...
随机推荐
- CLion和动态链接库
目录 生成链接库 链接库的使用 生成链接库 创建一个library项目 在项目中写好自己的代码 cmakelist cmake_minimum_required(VERSION 3.21) proje ...
- Kettle:跨库(SQLServer->PostgreSQL)同步多张表数据的详细设计过程
〇.参考地址 1.多个Excel实现同步 https://www.wangt.cc/2021/05/kettle%E5%A4%9A%E4%B8%AA%E8%A1%A8%E4%B8%80%E8%B5%B ...
- Docker进阶-Dockerfile建立一个自定义的镜像执行自定义进程
前言 docker对我来说是一个很方便的工具,,上一篇文章也写了docker基本的一些使用,这篇文章重点描述一下Dockerfile的使用,从零建立一个自己定制化的镜像,并可以执行我们需要的任务. 作 ...
- 一文带你入木三分地理解字符串KMP算法(next指针解法)
1. KMP算法简介 温馨提示:在通篇阅读完并理解后再看简介效果更佳 以下简介由百度百科提供https://baike.baidu.com/item/KMP%E7%AE%97%E6%B3%95/109 ...
- JavaScript:是一种什么样的编程语言?
有关JavaScript的发展历程,百度百科上已经说得很清楚了,这里不赘述,只是想谈一下我刚刚接触JS的一些感触. 作为后端java开发者,初次学习JS的时候,真的觉得JS非常的不严谨,很混乱.由于它 ...
- c++随笔测试(Corner of cpp)
在c++17下,程序的输出是什么?(有可能编译出错,有可能输出未知,有可能是未定义行为) 点击查看代码 #include<iostream> void foo(unsigned int) ...
- ubuntu系统wireshark源码编译与安装
官网:https://www.wireshark.org/ 官方文档:Wireshark · Documentation 一 介绍 wireshark[1]是一款抓包工具.wireshark的GUI( ...
- 速记·python 123章
第一.二.三章 初识python 1.1 Python的概述 开发环境:Python 开发工具:IDLE(Python自带) 1.python的特点:代码简单.开发速度快.容易学习:有丰富的库:&qu ...
- [python]《Python编程快速上手:让繁琐工作自动化》学习笔记5
1. 处理CSV文件笔记(第14章) (代码下载) 本文主要在python下介绍CSV文件,CSV 表示"Comma-Separated Values(逗号分隔的值)",CSV文件 ...
- Auto-Job任务调度框架
Auto-Job 任务调度框架 一.背景 生活中,业务上我们会碰到很多有关作业调度的场景,如每周五十二点发放优惠券.或者每天凌晨进行缓存预热.亦或每月定期从第三方系统抽数等等,Spring和java目 ...