使用 Apache Poi 将结果集从 Java 数据库导出到 Excel
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24933868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exporting Resultset from Java database to Excel using Apache Poi
提问by user3027085
Help am stucked on this project of exporting from result set to excel..previous solutions here haven't answered my questions but they have helped..here is my code so far it only displays a row in the database. My Code
帮助我坚持从结果集导出到 excel 的这个项目..以前的解决方案在这里没有回答我的问题,但他们有帮助..这是我的代码,到目前为止它只在数据库中显示一行。我的代码
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
public class Plexada2 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Storeway","root", "");
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("Select * from Storeway.order");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("lawix10");
Row row = sheet.createRow(0);
int x=0;
while (rs.next()){
String crate_id= rs.getString(2);
String content=rs.getString(3);
String Order_type= rs.getString(4);
java.sql.Date date= rs.getDate(5);
String datex= String.valueOf(date);
row.createCell(0).setCellValue(crate_id);
row.createCell(1).setCellValue(content);
row.createCell(2).setCellValue(Order_type);
row.createCell(3).setCellValue(datex);
}
x+=1;
String yemi = "C:\Users\lawix10\Desktop\testlno9.xls";
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
}
采纳答案by SparkOn
Ahh its very difficult to inspect your code trying formatting it before you post it and Regarding your query try something like this.
啊,在发布代码之前尝试对其进行格式化是非常困难的,并且关于您的查询,请尝试这样的操作。
try {
Class.forName("driverName");
Connection con = DriverManager.getConnection("url", "user", "pass");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("Select * from tablename");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("lawix10");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell((short) 0).setCellValue("CellHeadName1");
rowhead.createCell((short) 1).setCellValue("CellHeadName2");
rowhead.createCell((short) 2).setCellValue("CellHeadName3");
int i = 1;
while (rs.next()){
HSSFRow row = sheet.createRow((short) i);
row.createCell((short) 0).setCellValue(Integer.toString(rs.getInt("column1")));
row.createCell((short) 1).setCellValue(rs.getString("column2"));
row.createCell((short) 2).setCellValue(rs.getString("column3"));
i++;
}
String yemi = "g:/test.xls";
FileOutputStream fileOut = new FileOutputStream(yemi);
workbook.write(fileOut);
fileOut.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
回答by archana
can we have for loop to enter dynamic values into getString()?I tried this, but i couldnt fetch exact result.
我们可以使用 for 循环将动态值输入 getString() 吗?我试过这个,但我无法获取确切的结果。
My code: public static void excel(String appDB) { List headerValues=new ArrayList();
我的代码: public static void excel(String appDB) { List headerValues=new ArrayList();
XSSFWorkbook workbook = new XSSFWorkbook();
try {
setConnection(appDB);
String queryName="SELECT * FROM ALL_TABLES where table_name='table_name'";
Reporter.addStepLog("----------------------------------- " + queryName.toUpperCase()
+ "\n - Validation Start" + " -----------------------------------");
ps = con.prepareStatement(queryName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
Statement statement = con.createStatement();
XSSFSheet spreadsheet = workbook.createSheet("employedb");
ResultSet resultSet = statement.executeQuery("select * from all_tab_columns where table_name='table_name'");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
int cc=resultSet.getMetaData().getColumnCount();
for(int i=1;i<=cc;i++)
{
String headerVal=resultSet.getMetaData().getColumnName(i);
headerValues.add(headerVal);
cell = row.createCell(i-1);
cell.setCellValue(resultSet.getMetaData().getColumnName(i));
}
System.out.println(headerValues);
int i = 1;
while (resultSet.next())
{
for(int j=1;j<=cc;j++)
{
System.out.println(resultSet.getString(j));
XSSFRow row1 = spreadsheet.createRow((short) i);
row1.createCell((short) i).setCellValue(resultSet.getString(resultSet.getMetaData().getColumnName(j)));
i++;
}
}
FileOutputStream out = new FileOutputStream(new File("S:\Downloads\excel.xlsx"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xlsx written successfully");
}catch(Exception e){}
}
回答by archana
Above issue got resolved.
以上问题得到解决。
public static void excel(String appDB)
{
List<String> headerValues=new ArrayList<String>();
XSSFWorkbook workbook = new XSSFWorkbook();
try {
setConnection(appDB);
String queryName="SELECT * FROM ALL_TABLES where table_name='table_name";
Reporter.addStepLog("----------------------------------- " + queryName.toUpperCase()
+ "\n - Validation Start" + " -----------------------------------");
ps = con.prepareStatement(queryName, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
rs = ps.executeQuery();
Statement statement = con.createStatement();
XSSFSheet spreadsheet = workbook.createSheet("employedb");
ResultSet resultSet = statement.executeQuery("select * from all_tab_columns where table_name='table_name'");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
int cc=resultSet.getMetaData().getColumnCount();
for(int i=1;i<=cc;i++)
{
String headerVal=resultSet.getMetaData().getColumnName(i);
headerValues.add(headerVal);
cell = row.createCell(i-1);
cell.setCellValue(resultSet.getMetaData().getColumnName(i));
}
System.out.println(headerValues);
int i = 1;
while (resultSet.next())
{
XSSFRow row1 = spreadsheet.createRow((short) i);
for(int p=0;p<headerValues.size();p++)
{
row1.createCell((short) p).setCellValue(resultSet.getString(headerValues.get(p)));
}
i++;
}
FileOutputStream out = new FileOutputStream(new File("S:\Downloads\excel.xlsx"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xlsx written successfully");
}catch(Exception e){}
}
回答by firegloves
I suggest another solution, taking advantage of MemPOIlib. Take a look:
我建议另一种解决方案,利用MemPOI库。看一看:
public class Plexada2 {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:Storeway","root", "");
PreparedStatement prepStmt = conn.prepareStatement("Select * from Storeway.order");
File fileDest = new File("C:\Users\lawix10\Desktop\testlno9.xls");
new MempoiBuilder()
.setFile(fileDest)
.addMempoiSheet(new MempoiSheet(prepStmt))
.build()
.prepareMemptheitroadeportToFile()
.get();
} catch (Exception e) {
// TODO manage exception
}
}
}