maven依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
</dependencies>
java代码
如果感觉代码粗糙,可以自行改一下,其中$1是sql中的参数,根据情况是否添加,并且里面的参数可以有多个$1...$n,但是需要略改代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import javax.swing.JOptionPane;
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.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
public class ExportExcel {
public static void main(String[] args) {
System.out.println("程序启动");
HSSFWorkbook book = new HSSFWorkbook();
CellStyle cellStyle = getTitleStyle(book, true, 12);
CellStyle cellStyle1 = getTitleStyle(book, false, 10);
// 1.获取文件路径,获取失败时,系统自动关闭
File f = acquireAndCheckDownloadFile(args);
String fileName = f.getName().replace(".txt", "");
String path = f.getParent() + "\\" + fileName + ".xls";
try {
// 多个结果级
FileInputStream in = new FileInputStream(f);
byte[] b = new byte[(int) f.length()];
in.read(b);
String temp = new String(b);
String[] sqlSplit = temp.split("\r\n");
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection(
"jdbc:mysql://" + args[1]
+ "?useUnicode=true&characterEncoding=utf-8&useSSL=false&useOldAliasMetadataBehavior=true",
args[2], args[3]);
for (String sql : sqlSplit) {
String[] split = sql.split(":");
// 分别创建对应的执行类
Statement createStatement = con.createStatement();
System.out.println("执行sql:" + split[1]);
ResultSet rs = null;
//参数
if(split[1].contains("$1")) {
rs = createStatement.executeQuery(split[1].replace("$1", args[4]));
}else {
rs = createStatement.executeQuery(split[1]);
}
HSSFSheet sheet = book.createSheet(split[0]);
ResultSetMetaData rsmd = rs.getMetaData();// 得到结果集的字段名
int c = rsmd.getColumnCount();// 得到数据表的结果集的字段的数量
// 生成表单的第一行,即表头
HSSFRow row0 = sheet.createRow(0);// 创建第一行
for (int i = 0; i < c; i++) {
HSSFCell cel = row0.createCell(i);// 创建第一行的第i列
// System.out.println(rsmd.getColumnName(i + 1));
sheet.setColumnWidth(i, rsmd.getColumnName(i + 1).getBytes().length * 5 * 256);
// 单元格字体居中、并设置字体颜色
cel.setCellStyle(cellStyle);
cel.setCellValue(rsmd.getColumnName(i + 1));
}
// 将数据表中的数据按行导入进Excel表中
int r = 1;
while (rs.next()) {
HSSFRow row = sheet.createRow(r++);// 创建非第一行的其他行
for (int i = 0; i < c; i++) {// 仍然是c列,导入第r行的第i列
HSSFCell cel = row.createCell(i);
cel.setCellStyle(cellStyle1);
// 以下两种写法均可
// cel.setCellValue(rs.getString(rsmd.getColumnName(i+1)));
cel.setCellValue(rs.getString(i + 1));
}
}
// 用文件输出流类创建名为table的Excel表格
FileOutputStream out = new FileOutputStream(path);
book.write(out);// 将HSSFWorkBook中的表写入输出流中
book.close();
}
in.close();
System.out.println("执行结束");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 检查和获取文件
*
* @param arg
* @return
*/
private static File acquireAndCheckDownloadFile(String[] arg) {
if (arg == null || arg.length <= 0) {
alertAndExit("请指定参数 !");
}
// 获取本地文件
String filePath = arg[0];
File file = new File(filePath);
if (!file.exists()) {
alertAndExit("文件不存在!");
}
if (!file.isFile()) {
alertAndExit("文件不存在!");
}
if (!file.getName().contains(".txt")) {
alertAndExit("文件后缀必须是txt文件!");
}
return file;
}
/**
* 提示并且退出
*
* @param msg
*/
private static void alertAndExit(String msg) {
JOptionPane.showMessageDialog(null, msg);
System.exit(0);
}
/**
* 加粗,垂直居中
*
* @param wb
* @param isBold
* @param FontSize
* @return
*/
public static CellStyle getTitleStyle(Workbook wb, Boolean isBold, int FontSize) {
// 标题样式(加粗,垂直居中)
CellStyle cellStyle = wb.createCellStyle();
center(cellStyle);
Font font = wb.createFont();
// 加粗
font.setBold(isBold);
// 设置标题字体大小
font.setFontHeightInPoints((short) FontSize);
cellStyle.setFont(font);
return cellStyle;
}
/**
* 样式居中
*
* @param cellStyle
*/
public static void center(CellStyle cellStyle) {
// 水平居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);
// 垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
}
}
程序执行
工具使用eclipse,这里需要添加参数(其他ide的自行百度)
上面的参数是main方法中参数值,如下图
需要执行的txt文件,格式如下
sheet页名称:select * from `user`
执行结果
还可以用别名如下:
sheet页名称:select id,username as '用户名',password as '密码' from `user`
执行结果
打包测试
通过eclipse的导出jar的功能,不是maven命令
然后一路finish即可
执行命令
java -jar -Dfile.encoding=utf-8 export.jar 写的sql的txt的路径 localhost:3306/database root 1234
扩展
可以根据需要更换数据库类型,例如oracle,sqlserver等等的jdbc的连接,只需添加对应maven依赖,同时将代码的url略加修改就可以导出不通数据库的数据到excel