本文主要是将Excel中的数据导入Mysql和将Mysql中的数据导入Excel
1、Excel导入Mysql
/**
*
* Excel导入Mysql
*
* @version 1.0
* @author wangcy
* @date 2019年6月26日 下午4:24:07
*/
public class ExcelToMysql {
static final String DB_URL = "jdbc:mysql://localhost:3306/test"; // 数据库 URL
static final String USER = "root"; // 数据库的用户名
static final String PASS = "123456"; // 数据库的密码
private static final String PATH = "d:\\2019日历.xlsx"; // Excel文件所在的路径
private static final String TABLE = "calendar"; // 数据库表名
private static List<String> FIELDLIST = Arrays.asList("data", "type"); // 数据库字段
public static void main(String[] args) {
Connection connection = null;
PreparedStatement pstmt = null;
try {
// 打开链接
System.out.println("连接数据库...");
connection = DriverManager.getConnection(DB_URL, USER, PASS);
StringBuffer sql = new StringBuffer("insert into ");
sql.append(TABLE);
sql.append("(");
for (int i = 0; i < FIELDLIST.size(); i++) {
sql.append(FIELDLIST.get(i) + ",");
}
sql.deleteCharAt(sql.length()-1);
sql.append(") values ");
// 拼接数据
List<Map<String, Object>> dataList = ExcelUtil.getExcelData(PATH);
if (dataList!=null && dataList.size()!=0) {
for (Map<String, Object> map : dataList) {
sql.append("(");
for (int i = 0; i < FIELDLIST.size(); i++) {
sql.append("'" + map.get(FIELDLIST.get(i)) + "',");
}
sql.deleteCharAt(sql.length()-1);
sql.append("),");
}
}
sql.deleteCharAt(sql.length()-1);
pstmt = (PreparedStatement) connection.prepareStatement(sql.toString());
pstmt.execute();
System.out.println("导入成功");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
2、Mysql导入Excel
/**
*
* Mysql导入Excel
*
* @version 1.0
* @author wangcy
* @date 2019年6月26日 下午4:24:23
*/
public class MysqlToExcel {
static final String DB_URL = "jdbc:mysql://localhost:3306/test"; // 数据库 URL
static final String USER = "root"; // 数据库的用户名
static final String PASS = "123456"; // 数据库的密码
private static String PATH = "d:\\2019日历.xlsx"; // Excel文件所在的路径
private static String FILE_NAME = "2019日历.xlsx"; // 文件名
private static final String TABLE = "calendar"; // 数据库表名
private static List<String> FIELDLIST = Arrays.asList("data", "type"); // 数据库字段
public static void main(String[] args) {
Connection connection = null;
PreparedStatement pstmt = null;
try {
// 打开链接
System.out.println("连接数据库...");
connection = DriverManager.getConnection(DB_URL, USER, PASS);
String sql = "SELECT * from " + TABLE;
pstmt = (PreparedStatement) connection.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(sql);
List<Map<String, Object>> dataList = new ArrayList<>();
while (rs.next()) {
Map<String, Object> paraMap = new HashMap<String, Object>();
for (int i = 0; i < FIELDLIST.size(); i++) {
paraMap.put(FIELDLIST.get(i), rs.getString(FIELDLIST.get(i)));
}
dataList.add(paraMap);
}
rs.close();
ExcelUtil.downloadExcel(FILE_NAME, PATH, FIELDLIST, FIELDLIST, dataList);
System.out.println("导出成功");
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
3、Excel工具类
public class ExcelUtil {
/**
*
* 方法描述:将dataList数据保存到Excel中
*
* @param excelName 文件名
* @param path 文件路径
* @param headList 表头
* @param fieldList 表头对应字段
* @param dataList 数据
*
* @author wangcy
* @date 2019年6月26日 下午4:35:38
*/
public static void downloadExcel(String excelName, String path, List<String> headList, List<String> fieldList, List<Map<String, Object>> dataList) {
Workbook workbook = null;
FileOutputStream outputStream = null;
try {
FileUtil.mkdir(path);
if (path.endsWith(".xls")) {
workbook = new HSSFWorkbook();
} else if (path.endsWith(".xlsx")) {
workbook = new XSSFWorkbook();
}
Sheet sheet = workbook.createSheet(excelName);
Row row_0 = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
Cell cell_i = row_0.createCell(i);
cell_i.setCellValue(headList.get(i));
}
if (dataList!=null && dataList.size()!=0) {
for (int i = 0; i < dataList.size(); i++) {
Row row = sheet.createRow(i+1);
for (int j = 0; j < fieldList.size(); j++) {
Cell cell = row.createCell(j);
cell.setCellValue(ObjectUtils.castString(dataList.get(i).get(fieldList.get(j)), "") );
}
}
}
outputStream = new FileOutputStream(path);
workbook.write(outputStream);
outputStream.flush();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook!=null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream!=null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
*
* 方法描述:获取Excel中的数据
*
* @param PATH Excel路径
* @return
*
* @author wangcy
* @date 2019年6月26日 下午5:58:51
*/
public static List<Map<String, Object>> getExcelData(String path) {
List<Map<String, Object>> dataList = new ArrayList<>();
Workbook workbook = null;
try {
// 输入文件
FileInputStream inputStream = new FileInputStream(path);
if (path.endsWith(".xls")) {
workbook = new HSSFWorkbook(inputStream);
} else if (path.endsWith(".xlsx")) {
workbook = new XSSFWorkbook(inputStream);
}
List<String> fieldList = new ArrayList<String>();
// 获取Excel文档中第一个表单
Sheet sheet = workbook.getSheetAt(0);
// 获取Excel第一行名称
Row row0 = sheet.getRow(0);
for (Cell cell : row0) {
fieldList.add(cell.toString());
}
int rows = sheet.getLastRowNum() + 1;
int cells = fieldList.size();
for (int i = 1; i < rows; i++) {
Row row = sheet.getRow(i);
Map<String, Object> paraMap = new HashMap<>();
for (int j = 0; j < cells; j++) {
Cell cell = row.getCell(j);
if (cell != null && !cell.equals("")) {
paraMap.put(fieldList.get(j), cell.toString());
}
}
dataList.add(paraMap);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dataList;
}
}
4、File工具类
public class FileUtil {
/**
*
* 方法描述:判断路径文件是否存在,如果不存在则创建
*
* @param path
*
* @author wangcy
* @date 2019年6月26日 下午4:44:51
*/
public static void mkdir(String path) {
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.exists()) {
file.delete();
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}