导入excel数据到数据库
1.上传excel到服务器
jsp页面代码
<form action="actionname" method="post" id="form1" enctype="multipart/form-data"> <input type="file" name="excel" id="fileExecl" class="inputFile" onchange="uploadFile(this)" size="1" title=""/>
<input type="button" value="导入excel" onclick="importExcel()"> <form>
js代码
function importExcel() {
var fileExecl = document.getElementById("fileExecl").value;
if(fileExecl==null||fileExecl==""){
alert("请选择excel文件");
return false;
}
document.getElementById("action").value="importExcel";
document.getElementById("form1").submit();
}
function uploadFile(importObj) {
var path = importObj.value;
var type = path.substring(path.lastIndexOf(".") + 1, path.length).toLowerCase();
if (type != "xlsx"&&type != "xls") {
alert("请上传xlsx或xls后缀的Excel");
importObj.value = "";
} else {
document.getElementById("action").value="importExcel";
}
}
action代码
private File excel;//上传的文件
private String excelFileName; // File属性名 + FileName固定的 private File uploadFile() {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(excel);
String uploadPath = this.getServletContext().getRealPath("/staticFiles");
//分解路径
//String filePath = getFileDirectory(uploadPath);
File destFile = new File(uploadPath, excelFileName);
os = new FileOutputStream(destFile);
byte[] buffer = new byte[400];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
return destFile;
} catch (FileNotFoundException e) {
logger.error(e, e);
} catch (IOException e) {
logger.error(e, e);
}
return null;
} public String importExcel() { //文件上传路径
File file = uploadFile();
String filePath = file.getPath();
//获取导出数据
ImportExcel importExcel = new ImportExcel();
List<String[]> importList = importExcel.getImportList(filePath);
//删除上传文件
if(file.isFile() && file.exists()) {
file.delete();
}
for (int i = 1; i < importList.size(); i++) {
String[] rowData = importList.get(i);
//rowData[0] excel中第一列数据
} return null;
}
解析excel代码 xls和xlsx两种格式,代码可以优化
public class ImportExcel {
/**
*
* @param filePath 文件路径
* @return excel中一行数据储存在一个数组String[]
*/
public List<String[]> getImportList(String filePath) {
List<String[]> rowsData = new ArrayList<String[]>();;
if(filePath.endsWith("xls")){
try {
boolean importData = false;
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(filePath));
HSSFSheet sheet = hwb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();// 获取表格的行数
for (int r = 0; r < rows; r++) { // 循环遍历表格的行
importData = false;
String cellValue = "";
HSSFRow row = sheet.getRow(r);
if (row != null) {
int cells =row.getLastCellNum();
String[] rowData = new String[cells];
for (int c = row.getFirstCellNum(); c < cells; c++) {
HSSFCell cell = row.getCell(c);
if (cell != null) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { // 判断单元格的值是否为字符串类型
cellValue = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { // 判断单元格的值是否为数字类型
cellValue = cell.getNumericCellValue() + "";
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { // 判断单元格的值是否为布尔类型
cellValue = cell.getStringCellValue();
} else {
cellValue = "";
}
}
if (cellValue.trim().length() > 0) {
importData = true;
}
rowData[c] = cellValue;
}
//数据全为空,不导入
if (r > 0 && !importData) {
continue;
}
rowsData.add(rowData);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}else if(filePath.endsWith("xlsx")){
try {
boolean importData = false;
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(
filePath)); // 创建对Excel工作簿文件的引用
XSSFSheet sheet = workbook.getSheetAt(0); // 创建对第一个工作表的引用,多个工作表暂未实现
int rows = sheet.getPhysicalNumberOfRows();// 获取表格的行数
for (int r = 0; r < rows; r++) { // 循环遍历表格的行
importData = false;
String cellValue = "";
XSSFRow row = sheet.getRow(r); // 获取单元格中指定的行对象
if (row != null) {
int cells = row.getPhysicalNumberOfCells();// 获取单元格中指定列对象
String[] rowData = new String[cells];
for (short c = 0; c < cells; c++) { // 循环遍历单元格中的列
XSSFCell cell = row.getCell((short) c); // 获取指定单元格中的列
if (cell != null) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { // 判断单元格的值是否为字符串类型
cellValue = cell.getStringCellValue();
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { // 判断单元格的值是否为数字类型
cellValue = cell.getNumericCellValue() + "";
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { // 判断单元格的值是否为布尔类型
cellValue = cell.getStringCellValue();
} else {
cellValue = "";
}
}
if (cellValue.trim().length() > 0) {
importData = true;
}
rowData[c] = cellValue;
}
//数据全为空,不导入
if (r > 0 && !importData) {
continue;
}
rowsData.add(rowData);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return rowsData;
}
}
导入excel数据到数据库的更多相关文章
- 【转】 如何导入excel数据到数据库,并解决导入时间格式问题
在办公环境下,经常会用到处理excel数据,如果用写程序导入excel数据到数据库那就太麻烦了,涉及解析excel,还要各种格式问题,下面简单利用数据库本身支持的功能解决这类导入问题. 准备 创建表 ...
- .net导入excel数据到数据库中
在开发过程中我们经常面临着需要将数据导出或者导入到系统中,例如一些生产管理系统,项目管理系统等等都会有这样的需求: 将excel数据到系统中思路:获取excel中每一行的数据,然后存入集合中,批量添加 ...
- java 使用poi 导入Excel 数据到数据库
由于我个人电脑装的Excel是2016版本的,所以这地方我使用了XSSF 方式导入 . 1先手要制定一个Excel 模板 把模板放入javaWeb工程的某一个目录下如图: 2模板建好了后,先实现模板下 ...
- PHP 导入Excel数据 到数据库
/** * 导入excel * @throws \PHPExcel_Exception * @throws \PHPExcel_Reader_Exception */ public function ...
- Web服务器与数据库服务器分离 导入 Excel数据至数据库
一般情况一般项目WEB服务器与数据库均部署在一台服务器,文件上传,数据导入在一台服务器完成.web服务器与数据库服务器分离,文件上传与数据导入将分布在两台服务器或多台服务器之间.本案例为两台服务器,具 ...
- java 对excel操作导入excel数据到数据库
加入jar包jxl.jar ===================services层掉用工具类==================================== // 导入 public Lis ...
- 如何批量导入excel数据至数据库(MySql)--工具phpMyAdmin
之前由于数据储存使用excel保存了所有数据,经过初步数据筛选,数据量近4000条.一条一条录入数据库显然是不可行的.以下是我所操作的步骤: 1.只保留excel的数据部分,去除第一行的具体说明 2. ...
- MYSQL 导入Excel数据到数据库中
1,先把excel的数据整理整齐,如每列都要保持同样的格式:就一列一列的数据: 2,导出excel的数据为CSV格式,即把excel的数据另存为xxxx.csv;: 3,用EditPlus工具将xxx ...
- Winform导入Excel数据到数据库
public partial class ImportExcel : Form { AceessHelpers accessHelper = new AceessHelpers(); public I ...
随机推荐
- 我为什么还要造轮子?欠踹?Monk.UI表单美化插件诞生记!
背景 目前市场上有很多表单美化的UI,做的都挺不错,但是他们都有一个共同点,那就是90%以上都是前端工程师开发的,导致我们引入这些UI的时候,很难和程序绑定.所以作为程序员的我,下了一个决定!我要自己 ...
- 上传本地代码到github
第一步:建立git仓库 cd到你的本地项目根目录下,执行git命令git init第二步:将项目的所有文件添加到仓库中git add .如果想添加某个特定的文件,只需把.换成特定的文件名即可第三步:将 ...
- Html页面禁止鼠标左键复制
<body leftmargin=0 topmargin=0 oncontextmenu='return false' ondragstart='return false' onselectst ...
- 解决Unable to create new native thread
两种类型的Out of Memory java.lang.OutOfMemoryError: Java heap space error 当JVM尝试在堆中分配对象,堆中空间不足时抛出.一般通过设定J ...
- 第二轮冲刺-Runner站立会议03
今天做了什么:查看gridview与baseadapter适配器 明天准备做什么:继续gridview与baseadapter适配器 遇到的困难:暂无
- global name 'validate_on_submit' is not defined错误
原因就是validate_on_submit()方法是属于form的方法我使用的时候忘了form. 还有一个比较重要的是validate_on_submit()方法是wtf特有的而wtform是没有这 ...
- cnblog中添加数学公式支持
在博客中使用数学公式,是一件相对麻烦的事儿,大量的截图和插入图片不仅耗费极大的精力,而且影响写作体验. 虽然对于公式显示已经有多种解决办法,但大多数需要安装插件.而MathML这一雄心勃勃的网页数学语 ...
- 作为一名前端er,从武汉来到深圳三个月有感
来到深圳已经三个月了,从最开始的担心自己的能力不够怕不能够在深圳这个互联网产品及其发达的城市立足下来,到现在已经慢慢地拾起了一丁点的信心了 (虽然还有很多知识是不够的.但是相当于之前我的,我是觉得我已 ...
- seajs源码分析
seajs主要做了2件事 1.定义什么是模块,如何声明模块:id.deps.factory.exports ----define=function(id,deps,factory){return ex ...
- 【Tomcat 6.0官方文档翻译】—— 简介
Tomcat作为使用最多的web容器,研究其原理过程,对掌握java web开发有很重要的影响. 因此下定决心,从官方文档入手,好好学学web相关的知识. 介绍 本篇是Apache Tomca ...