在jsp中上传Exce并将Excel中内容保存到数据库

记录一个写了一天半的问题,前段js创建一个iframe,由里面的额form来使用jsp上传Excel同时将Excel保存到数据库

下面贴出了整个jsp,有些类涉及到了项目所以删除了

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="java.util.*,java.io.*"%>

<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%> 
<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%@page import="org.apache.poi.poifs.filesystem.POIFSFileSystem"%>  
<%@page import="org.springframework.web.multipart.commons.CommonsMultipartFile" %>

<%@page import="org.apache.commons.io.FileUtils" %>
<%@page import="org.apache.poi.ss.usermodel.Cell" %>
<%@page import="org.apache.poi.xssf.usermodel.XSSFCell" %>
<%@page import="org.apache.poi.xssf.usermodel.XSSFRow" %>
<%@page import="org.apache.poi.xssf.usermodel.XSSFSheet" %>
<%@page import="org.apache.poi.xssf.usermodel.XSSFWorkbook" %>

<html>
<head>
<title>uploadFile</title>
</head>
<body>
<%   

	FileStoreService fss =  ServiceFactory.getFileStoreSerivce();
	
	String serverPath = request.getRealPath("") + "/upload";
	String curTime = DateUtils.curDateTimeStr14();

	//最大文件大小
	long maxSize = 40000000;
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	upload.setHeaderEncoding("UTF-8");
	List items = upload.parseRequest(request);
	Iterator itr = items.iterator();
	while (itr.hasNext()) {
		FileItem item = (FileItem) itr.next();
		
		//由FileItem 装换为 File
		String fileName = item.getName();
		
		if(fileName == null){
			continue;
		}
		
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
		String newFileName = curTime + "_" +new Random().nextInt(1000) + "." + fileExt;
		
		
		File file = new File(serverPath, newFileName);
		//创建文件
		try{
			file.createNewFile();
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			
		}
		//FileItem 类写入file
		item.write(file);
				
		//创建Excel,读取文件内容
		XSSFWorkbook workbook = new XSSFWorkbook(FileUtils.openInputStream(file));

		//获取第一个工作表
		XSSFSheet sheet = workbook.getSheet("Sheet1");
		
		//获取sheet中第一行行号
		int firstRowNum = sheet.getFirstRowNum();
		//获取sheet中最后一行行号
		int lastRowNum = sheet.getLastRowNum();
		
		try {
			//循环插入数据
			for(int i=firstRowNum+1;i<=lastRowNum;i++){
				XSSFRow row = sheet.getRow(i);
				
				Map insertMap = new HashMap();
				
				XSSFCell ITEMID = row.getCell(0);    //物料代码
				if(ITEMID!=null){
					ITEMID.setCellType(Cell.CELL_TYPE_STRING);
					insertMap.put("ITEMID",(ITEMID.getStringCellValue()));
				}
				
				XSSFCell ITEMNAME = row.getCell(1);		//物料名称
				if(ITEMNAME!=null){
					ITEMNAME.setCellType(Cell.CELL_TYPE_STRING);
					insertMap.put("ITEMNAME",(ITEMNAME.getStringCellValue()));
				}
				
				XSSFCell DATATIME = row.getCell(2);		//日期       格式为 yyyy-MM-dd   
				if(DATATIME!=null){
					DATATIME.setCellType(Cell.CELL_TYPE_STRING);
					insertMap.put("DATATIME",(DATATIME.getStringCellValue()));
				}
				
				XSSFCell DATAVAL = row.getCell(3);       //价格  
				if(DATAVAL!=null){
					DATAVAL.setCellType(Cell.CELL_TYPE_STRING);
					insertMap.put("DATAVAL",(DATAVAL.getStringCellValue()));
				}
				
				XSSFCell COMPANYNAME = row.getCell(4);	//公司别    
				if(COMPANYNAME!=null){
					COMPANYNAME.setCellType(Cell.CELL_TYPE_STRING);
					insertMap.put("COMPANYNAME",(COMPANYNAME.getStringCellValue()));
				}
				
				insertMap.put("REC_CREATOR",UserUtils.getUserLoginName());
				insertMap.put("REC_CREATOR_CNAME", UserUtils.getUserLoginName());
				insertMap.put("REC_CREATE_TIME",curTime);
				
				System.out.println(insertMap);
				
				dao.insert("PRLY2011.insert",insertMap);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			file.delete();
		}
		
		
	}	
%>
</body>
</html>

上传的Excel的内容为
jsp中上传Excel格式

eclipse开发,jdk1.6,很老,老得不能再老,很烦

其中jsp中部分方法不能用可以评论留言给我

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Apache POI 库来读取 Excel 文件的数据,然后使用 JDBC 将数据插入到数据库。 以下是一个简单的示例代码: ```java import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class ExcelToDatabase { public static void main(String[] args) { String fileName = "path/to/excel/file.xlsx"; String url = "jdbc:mysql://localhost:3306/test"; String username = "root"; String password = "password"; String insertQuery = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)"; try (FileInputStream inputStream = new FileInputStream(fileName); Workbook workbook = WorkbookFactory.create(inputStream); Connection connection = DriverManager.getConnection(url, username, password); PreparedStatement statement = connection.prepareStatement(insertQuery)) { Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { Cell cell1 = row.getCell(0); Cell cell2 = row.getCell(1); Cell cell3 = row.getCell(2); statement.setString(1, cell1.getStringCellValue()); statement.setDouble(2, cell2.getNumericCellValue()); statement.setBoolean(3, cell3.getBooleanCellValue()); statement.executeUpdate(); } System.out.println("Data imported successfully!"); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例,你需要将 `path/to/excel/file.xlsx` 替换为实际的 Excel 文件路径,将 `table_name` 替换为实际的数据库表名,将 `column1`, `column2`, `column3` 替换为实际的数据库表列名。你还需要将数据库连接 URL、用户名和密码替换为实际值。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值