最近项目中经常需要把多个数据库表中的参数进行处理转化为指定的sql,由于工作量太大,决定写一个小工具类
package com.zhz.tools;
import java.awt.*;
/**
* @Author:zhanghuazheng
* @Date:Created in 13:57 2019/5/17
* @Describe:
**/
public class Main {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ReadFile window = new ReadFile();
// window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
package com.zhz.tools;
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 javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
/**
* @Author:zhanghuazheng
* @Date:Created in 13:58 2019/5/17
* @Describe:
**/
public class ReadFile {
public JFrame frame;
private String CHOOSE_FILE_PATH="";
File file;
JTextField inPath;
JTextField outPath;
JTextField sqlContet;
public ReadFile(){
initialize();
}
/**
* 读取界面视图
*/
private void initialize() {
//1.设置面板
frame =new JFrame();
frame.setTitle("百宝箱");
frame.setSize(500, 500);
frame.setLocation(500, 200);
frame.setLayout(null);
//2.设置选择上传文件
JFileChooser fileChooser = new JFileChooser("文件选择器");
// fileChooser.setBounds(0,300,400,500);
fileChooser.addChoosableFileFilter(new FileFilter() {
@Override
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".txt");
}
@Override
public String getDescription() {
return "222";
}
});
JButton bOpen = new JButton("选择文件");
bOpen.setBounds(50, 250, 100, 30);
bOpen.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = fileChooser.showOpenDialog(frame);
file = fileChooser.getSelectedFile();
inPath.setText(file.getAbsolutePath());
// getChoiceFile(file);
if (returnVal == JFileChooser.APPROVE_OPTION) {
JOptionPane.showMessageDialog(frame, "计划打开文件:" + file.getAbsolutePath());
}
}
});
JLabel inLabel = new JLabel("源文件路径:");
inLabel.setBounds(10,80,100,25);
inPath = new JTextField();
// inPath.setEnabled(false);
inPath.setBounds(115, 80, 300, 25);
JLabel outLabel = new JLabel("目标文件路径:");
outLabel.setBounds(10,120,100,25);
outPath = new JTextField();
outPath.setBounds(115, 120, 300, 25);
JLabel initLabel = new JLabel("要转化的sql:");
initLabel.setBounds(10,170,100,25);
sqlContet = new JTextField("INSERT INTO om_attr_value (PARAM_KEY, PARAM_NAME, PARAM_VALUE, VALUE_DESC, USER_ID, TIME_STAMP) VALUES ('");
sqlContet.setBounds(115, 170, 300, 25);
/**
* 转换按钮
*/
JButton conver = new JButton("转换");
conver.setBackground(Color.blue);
conver.setBounds(300,250,100,30);
conver.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String ipath = inPath.getText();
String oPath = outPath.getText();
System.out.println("path="+ipath);
if(ipath==null ||"".equals(ipath)){
JOptionPane.showMessageDialog(frame, "源文件路径不能为空,请先选择文件");
}
praseExcel(ipath,sqlContet.getText(),oPath);
}
});
/**
* 获取当前操作系统的桌面路径
*/
File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
String desktopPath = desktopDir.getAbsolutePath();
outPath.setText(desktopPath+File.separator+"myTxt.sql");
frame.add(fileChooser);
frame.add(bOpen);
frame.add(inLabel);
frame.add(outLabel);
frame.add(initLabel);
frame.add(sqlContet);
frame.getContentPane().add(inPath);
frame.getContentPane().add(outPath);
frame.getContentPane().add(conver);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* 获取选择文件的路径
*/
public String getChoiceFile(File file){
return file.getAbsolutePath();
}
/**
* 读取选择的文件
* @param excelPath
* @param initSql 初始化sql
* @param outPath 输出路径
*/
public static void praseExcel(String excelPath,String initSql,String outPath){
//final String INIT_SQL = "INSERT INTO om_attr_value (PARAM_KEY, PARAM_NAME, PARAM_VALUE, VALUE_DESC, USER_ID, TIME_STAMP) VALUES ('";
//final String OUT_FILE_PATH = "H:\\zx\\insert.sql";
final String INIT_SQL=initSql;
final String OUT_FILE_PATH = outPath;
try {
File excel = new File(excelPath);
if (excel.isFile() && excel.exists()) { //判断文件是否存在
String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!!!!!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
FileInputStream fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fis);
}else {
System.out.println("文件类型错误!");
return;
}
//开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0
int firstRowIndex = sheet.getFirstRowNum()+1; //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex);
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
StringBuffer str = new StringBuffer();
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
str = new StringBuffer();
System.out.println("INIT_SQL="+INIT_SQL);
str.append(INIT_SQL);
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
if(cIndex==lastCellIndex-1){
str.append(cell.toString()+"\', NULL, NULL, NULL);"+"\r\n");
}else {
str.append(cell.toString()+"\',\'");
}
}
}
System.out.println(str.toString());
System.out.println("outPath="+outPath);
System.out.println("OUT_FILE_PATH="+OUT_FILE_PATH);
writeToTxt(str.toString(),OUT_FILE_PATH);
}
}
} else {
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 写文件到指定的路径
*/
public static void writeToTxt(String inPut,String outPath){
File file = new File(outPath);
BufferedWriter bw=null;
try {
if(!file.exists()){
file.createNewFile();
}
FileWriter fw = new FileWriter(file,true);
bw = new BufferedWriter(fw);
bw.write(inPut);
System.out.println("文件写入成功");
}catch (Exception e){
e.printStackTrace();
}finally {
if(bw!=null){
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
三、运行结果图
由于时间短,代码写的有点粗糙