用java将excel导入数据库

          本人需要对每天发送的定时邮件取近30天的数据导入数据库,因此excel文件名有一定的特点,比较好删选。写这博客主要做个笔记,因为java还是入门阶段

package com.yiwugou.analysis.words;

import java.io.File;
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
  

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
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.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;  

import com.yiwugou.analysis.util.DatabaseHelper;
import com.yiwugou.analysis.util.DateTimeUtil;
import com.yiwugou.analysis.util.SqlHelper;
import com.yiwugou.analysis.words.dao.ExcelToDBDao;
  
public class ExcelToDB extends SqlHelper { 
	
	Connection conn;
	
    public static void main(String[] args) throws IOException {  
    	String srcFile="D:\\Users\\Administrator\\Desktop\\excel";
    	ExcelToDB e=new ExcelToDB();
    	e.read(srcFile);
    }  
    
    public List<String> file(String srcFile){  
        File file=new File(srcFile);  
        if(!file.isDirectory()){  
            System.out.println("这不是一个目录");  
        }  
        File[] listfile=file.listFiles();
        List<String> fileFullName=new ArrayList<String>();
        //对于日期和文件的获取,是我的文件目录下文件名的要求,其他人可自行处理
        //excel文件特点:xxxxx_xxxxxx_xxxxxxx_20150620_20150621.xlsx
        Calendar cal = Calendar.getInstance();//获取当前日期
    	Calendar cal31=DateTimeUtil.getNdayBeforeToday(31);//获取31天前的日期
		String dayNow= getDateStrFromTS(cal);//将Calendar日期格式转为字符串,如:"20150621"
		String d31= getDateStrFromTS(cal31);		
        for (int i = 0; i < listfile.length; i++) {  
            if(listfile[i].isFile()){  
                String filename=listfile[i].getName();  //获取excel文件名
              String dayStr=filename.substring(21,29);  //截取第一个日期表示文件的当天
              if(dayStr.compareTo(d31)>=0&dayStr.compareTo(dayNow)<0){//要求获取近30天的文件
            	  fileFullName.add(filename);
              }           
            }  
        }  
        return fileFullName;
    }
    
    
    
    /*读取excel数据*/
    public void read(String srcFile) throws IOException  
    {  
    	List<String> fileFullName=file(srcFile);
    	for(String filename:fileFullName){
    		String dayStr=filename.substring(21,29);
    		InputStream stream = new FileInputStream(srcFile+File.separator+filename); 
    		Workbook wb = null;  
	        if (filename.endsWith(".xls")) {  
	            wb = new HSSFWorkbook(stream);  
	        }  
	        else if (filename.endsWith(".xlsx")) {  
	            wb = new XSSFWorkbook(stream);  
	        }  
	        else {  
	            System.out.println("您输入的excel格式不正确");  
	        }  
	        Sheet sheet1 = wb.getSheetAt(0);//读取第一张sheet表
	
	       for(int i=1;i<sheet1.getLastRowNum();i++){//从第二行开始,因为第一行是表头
	        	int searchNum=(int) sheet1.getRow(i).getCell(0).getNumericCellValue();//读取第1列,是int型
	        	String keyword=sheet1.getRow(i).getCell(4).getStringCellValue();//读取第5列,是String型
	        	insert(dayStr,keyword,searchNum);//数据库进行插入处理
	        }
    	}
       
    }  
    
    public void insert(String dayStr,String keyword,int searchNum){
    	Connection con =  getConnection();
    	String sql="insert into xxxxxxx_30days(dayStr,keyword,searchNum) values(?,?,?)";
		String[] paras={dayStr,keyword,String.valueOf(searchNum)};
        SqlHelper.executeUpdate(sql,paras,con);//<span style="font-family: Arial, Helvetica, sans-serif;">SqlHelper是韩顺平老师jdbc课程中的</span>

	}
    
    private Connection getConnection() {
		// TODO Auto-generated method stub
		try {
			if(conn==null||conn.isClosed())
			{
				String user = "数据库用户名";
				String password = "数据库密码";
				String url = "数据库的url";			 		
                                conn = getConnectionByParams(url,user,password);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}

      public String getDateStrFromTS(Calendar  cal) {
<span style="white-space:pre">		</span>// 返回用于数据库查询的日期时间字符串
<span style="white-space:pre">			</span> String monthStr =  cal.get(Calendar.MONTH)+1<10?"0"+(cal.get(Calendar.MONTH)+1):(cal.get(Calendar.MONTH)+1)+"";
<span style="white-space:pre">			</span>    String dateStr =  cal.get(Calendar.DAY_OF_MONTH)<10?"0"+cal.get(Calendar.DAY_OF_MONTH):cal.get(Calendar.DAY_OF_MONTH)+"";
<span style="white-space:pre">				</span>return <span style="white-space:pre">	</span>cal.get(Calendar.YEAR)+monthStr+dateStr;
<span style="white-space:pre">	</span>
<span style="white-space:pre">		</span>
<span style="white-space:pre">	</span>}
    
} 


可以使用Java中的Apache POI来读取Excel文件,并结合JDBC连接数据库将数据导入数据库中。 以下是一个简单的示例代码,假设你要将Excel中的数据导入到名为"table_name"的数据库表中: ```java import java.io.FileInputStream; import java.sql.Connection; 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.xssf.usermodel.XSSFWorkbook; public class ExcelToDatabase { public static void main(String[] args) { String jdbcURL = "jdbc:mysql://localhost:3306/database_name"; String username = "username"; String password = "password"; String excelFilePath = "path/to/excel/file.xlsx"; try (Connection connection = DriverManager.getConnection(jdbcURL, username, password); FileInputStream inputStream = new FileInputStream(excelFilePath); XSSFWorkbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); for (int i = 1; i <= sheet.getLastRowNum(); i++) { Row currentRow = sheet.getRow(i); Cell cell1 = currentRow.getCell(0); statement.setString(1, cell1.getStringCellValue()); Cell cell2 = currentRow.getCell(1); statement.setString(2, cell2.getStringCellValue()); Cell cell3 = currentRow.getCell(2); statement.setString(3, cell3.getStringCellValue()); statement.executeUpdate(); } System.out.println("Data imported successfully"); } catch (SQLException e) { System.out.println("Database error: " + e.getMessage()); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } ``` 请替换代码中的数据库连接信息、Excel文件路径、表名和列名等信息,以适应你的情况。注意,代码中默认将Excel文件的第一行视为表头,因此从第二行开始读取数据。 另外,需要在项目中引入Apache POI和MySQL JDBC驱动的依赖。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值