HTML
<a class="easyui-linkbutton l-btn-new-plain" data-options="iconCls:'icon-remove'" οnclick="Import()">导入</a>
<input type="file" id="fileTxt2" οnchange="isHaveFile()" style="display:none" />
JS
function Import() {
$("#fileTxt2").click();
}
function isHaveFile() {
var path = $("#fileTxt2").val();
if (path != "") {
uploadFile();
}
//datagridReload();
}
function uploadFile() {
$("#jdtDiv").css("display", "inline-block");
var fd = null;
try {
fd = new FormData();
} catch (e) {
alert('当前导入需要选择非IE8的浏览器,建议用其他浏览器!');
$("#jdtDiv").hide();
return;
}
fd.append("fileInput", document.getElementById('fileTxt2').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "UploadExcel");//FileUploads
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
}
else {
document.getElementById('percentNumber').innerHTML = '不支持进度计算';
}
}
function uploadComplete(evt) {
var serverMsg = evt.target.responseText;
alert(serverMsg);
$("#fileTxt2").val("");
$("#jdtDiv").hide();
}
function uploadFailed(evt) {
var serverMsg = evt.target.responseText;
AlertMsg(serverMsg);
$("#jdtDiv").hide();
}
function uploadCanceled(evt) {
alert('用户取消了上传或者浏览器删除了连接!');
$("#jdtDiv").hide();
}
MVC
IWorkbook workbook = null;
public ActionResult UploadExcel()
{
HttpPostedFileBase filebase = Request.Files[0];
string type = "2003";
if (filebase == null)
{
return Content("没有文件");
}
else
{
if (filebase.FileName.Contains(".xlsx"))
type = "2007";
}
string backMsg = ImportExcelToDB(filebase.InputStream, type);
return Content(backMsg);
}
public string ImportExcelToDB(Stream steam, string type)
{
AdminLoginUser user = Session["user"] as AdminLoginUser;
string importDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
try
{
if (type == "2003")
workbook = new HSSFWorkbook(steam);
else
workbook = new XSSFWorkbook(steam);
if (workbook != null)
{
ISheet sheet = workbook.GetSheetAt(0);
int rows = sheet.PhysicalNumberOfRows;//获取行数
for (int index = 1; index < rows; index++)
{
IRow row = sheet.GetRow(index);
try
{
if (row == null)
{
continue;
}
//tb_Question tb_q = new tb_Question();
//tb_q.IType = row.Cells[0].ToString().Trim().Contains("单选") ? 1 : row.Cells[0].ToString().Trim().Contains("多选") ? 2 : 3;
//tb_q.Title = row.Cells[1].ToString().Trim();
}
catch (Exception ex)
{
return "数据格式有误:第" + index + "行。";
}
}
}
steam.Close();
steam.Dispose();
return "导入成功";
}
catch (Exception ex)
{
string msg = ex.Message.Replace("\r\n", "");
return msg;
}
}