java解析excel进行导入数据库操作

工具类 

package com.inxedu.os.common.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class ExcelTool {
    public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
    public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
    public static final String EMPTY = "";
    public static final String POINT = ".";
    public static SimpleDateFormat sdf =   new SimpleDateFormat("yyyy/MM/dd");
    /**
     * 获得path的后缀名
     * @param path
     * @return
     */
    public static String getPostfix(String path){
        if(path==null || EMPTY.equals(path.trim())){
            return EMPTY;
        }
        if(path.contains(POINT)){
            return path.substring(path.lastIndexOf(POINT)+1,path.length());
        }
        return EMPTY;
    }
    /**
     * 单元格格式
     * @param hssfCell
     * @return
     */
    @SuppressWarnings({ "static-access", "deprecation" })
    public static String getHValue(HSSFCell hssfCell){
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            String cellValue = "";
            if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
                Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
                cellValue = sdf.format(date);
            }else{
                DecimalFormat df = new DecimalFormat("#.##");
                cellValue = df.format(hssfCell.getNumericCellValue());
                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
                if(strArr.equals("00")){
                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
                }
            }
            return cellValue;
        } else {
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }
    /**
     * 单元格格式
     * @param xssfCell
     * @return
     */
    public static String getXValue(XSSFCell xssfCell){
        if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(xssfCell.getBooleanCellValue());
        } else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            String cellValue = "";
            if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
                Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
                cellValue = sdf.format(date);
            }else{
                DecimalFormat df = new DecimalFormat("#.##");
                cellValue = df.format(xssfCell.getNumericCellValue());
                String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
                if(strArr.equals("00")){
                    cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
                }
            }
            return cellValue;
        } else {
            return String.valueOf(xssfCell.getStringCellValue());
        }
    }
    /**
     * 自定义xssf日期工具类
     * @author lp
     *
     */
    static class XSSFDateUtil extends DateUtil {
        protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
            return DateUtil.absoluteDay(cal, use1904windowing);
        }
    }
}

工具类

package com.inxedu.os.common.util;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

import java.util.ArrayList;
import java.util.List;


public class ExcelUtils {

    public static int totalRows; //sheet中总行数
    public static int totalCells; //每一行总单元格数


    /**
     * read the Excel .xlsx,.xls
     * @param file jsp中的上传文件
     * @return
     * @throws IOException
     */
    public static List<ArrayList<String>> readExcel(File file) throws IOException {
        if(file==null){
            return null;
        }else{
            String postfix = ExcelTool.getPostfix(file.getName());
            if(!ExcelTool.EMPTY.equals(postfix)){
                if(ExcelTool.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
                    return readXls(file);
                }else if(ExcelTool.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
                    return readXlsx(file);
                }else{
                    return null;
                }
            }
        }
        return null;
    }


    /**
     * read the Excel 2010 .xlsx
     * @param file
     * @return
     * @throws IOException
     */
    @SuppressWarnings("deprecation")
    public static List<ArrayList<String>> readXlsx(File file){
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
        // IO流读取文件
        InputStream input = null;
        XSSFWorkbook wb = null;
        ArrayList<String> rowList = null;
        try {
            input = new FileInputStream(file);
            // 创建文档
            wb = new XSSFWorkbook(input);
            //读取sheet(页)
            for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
                XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
                if(xssfSheet == null){
                    continue;
                }
                totalRows = xssfSheet.getLastRowNum();
                //读取Row,从第二行开始
                for(int rowNum = 0;rowNum <= totalRows;rowNum++){
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if(xssfRow!=null){
                        rowList = new ArrayList<String>();
                        totalCells = xssfRow.getLastCellNum();
                        //读取列,从第一列开始
                        for(int c=0;c<=totalCells+1;c++){
                            XSSFCell cell = xssfRow.getCell(c);
                            if(cell==null){
                                rowList.add(ExcelTool.EMPTY);
                                continue;
                            }
                            rowList.add(ExcelTool.getXValue(cell).trim());
                        }
                        list.add(rowList);
                    }
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
    /**
     * read the Excel 2003-2007 .xls
     * @param file
     * @return
     * @throws IOException
     */
    public static List<ArrayList<String>> readXls(File file){
        List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
        // IO流读取文件
        InputStream input = null;
        HSSFWorkbook wb = null;
        ArrayList<String> rowList = null;
        try {
            input = new FileInputStream(file);
            // 创建文档
            wb = new HSSFWorkbook(input);
            //读取sheet(页)
            for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
                HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
                if(hssfSheet == null){
                    continue;
                }
                totalRows = hssfSheet.getLastRowNum();
                //读取Row,从第二行开始
                for(int rowNum = 0;rowNum <= totalRows;rowNum++){
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    if(hssfRow!=null){
                        rowList = new ArrayList<String>();
                        totalCells = hssfRow.getLastCellNum();
                        //读取列,从第一列开始
                        for(short c=0;c<=totalCells+1;c++){
                            HSSFCell cell = hssfRow.getCell(c);
                            if(cell==null){
                                rowList.add(ExcelTool.EMPTY);
                                continue;
                            }
                            rowList.add(ExcelTool.getHValue(cell).trim());
                        }
                        list.add(rowList);
                    }
                }
            }
            return list;
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



}

 

控制层

@RequestMapping(value = "o_import.do",method = RequestMethod.POST)
	public String importXls(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "file", required = false) MultipartFile file){
		try {
			String originalFilename = file.getOriginalFilename();
		String ext = FileUploadUtils.getSuffix(originalFilename);
		String filePath = getPath(request,ext);
		File files = new File(CommonConstants.projectRootDir+filePath);
		if(!files.getParentFile().exists()){
			files.getParentFile().mkdirs();
		}
		//保存文件
		file.transferTo(files);

			//list为excel数据集合
			List<ArrayList<String>>  list = ExcelUtils.readExcel(files);
			Article article=new Article();
			ArticleContent articleContent=new ArticleContent();
			for(int i=1;i<list.size();i++){
					article.setTitle(list.get(i).get(0));
					article.setSummary(list.get(i).get(1));
					article.setSource(list.get(i).get(2));
					article.setAuthor(list.get(i).get(3));
					article.setType(2);
					article.setClickNum(0);
					article.setPraiseCount(0);
					article.setPublishTime(new Date());
					article.setCreateTime(new Date());
					article.setSort(0);
					int articleId = articleService.createArticle(article);
					// 添加文章内容
					articleContent.setArticleId(articleId);
					articleContent.setContent(list.get(i).get(4));
					articleService.addArticleContent(articleContent);
			}
			//删除文件
			File deleteFile = new File(CommonConstants.projectRootDir+filePath);
			if (deleteFile.exists() && deleteFile.isFile()
					&& deleteFile.delete() == true) {

			}

		} catch (Exception e) {
			e.printStackTrace();
			return "导入失败";
		}
		return "导入成功";
	}
	private String getPath(HttpServletRequest request,String ext){
		String filePath = "/images/upload/";
		filePath+= CommonConstants.projectName;
		filePath+="/"+ DateUtils.toString(new Date(), "yyyyMMdd")+"/"+System.currentTimeMillis()+"."+ext;
		return filePath;
	}

 

 应该是这几个依赖但是下面删了也不行了,就留着了

 

 到这用postman测试是可以添加数据到数据库了

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用 Apache POI 库来解析 Excel 表中的数据,并使用 JDBC 将数据导入数据库。是一个简单的 Java 代码示: 首先,确保你已经将 POI 和 JDBC 相关的 JAR 文件添加到你的项目中。 ```java import java.FileInputStream; import java.sql; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; 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.xssf.usermodel.XSSFWorkbook; public class ExcelImporter { public static void main(String[] args) { String excelFilePath = "path/to/your/excel/file.xlsx"; try (FileInputStream inputStream = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); int rowCount = 0; for (Row row : sheet) { if (rowCount == 0) { rowCount++; continue; } String column1 = row.getCell(0).getStringCellValue(); int column2 = (int) row.getCell(1).getNumericCellValue(); // 获取其他列的数据 // 将数据插入数据库 insertToDatabase(column1, column2); rowCount++; } System.out.println("数据导入成功!"); } catch (Exception e) { e.printStackTrace(); } } private static void insertToDatabase(String column1, int column2) { String url = "jdbc:mysql://localhost:3306/your_database"; String username = "your_username"; String password = "your_password"; try (Connection connection = DriverManager.getConnection(url, username, password)) { String sql = "INSERT INTO your_table (column1, column2) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, column1); statement.setInt(2, column2); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上面的示例中,你需要将 `path/to/your/excel/file.xlsx` 替换为你实际的 Excel 文件路径。此外,你还需要根据你的数据库设置更新 `url`、`username`、`password`、`your_database` 和 `your_table`。 这个示例假设 Excel 表的第一行为标题,从第二行开始是数据。你可以根据需要调整代码以适应不同的表格结构。同时,你可以根据你的数据库表结构调整 `insertToDatabase()` 方法中的 SQL 语句和参数设置。 请确保你已正确引入所需的库和驱动程序,并在执行代码之前设置好数据库连接信息。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值