Java USES poi to import data from the database into Excel

  • 2020-04-01 01:47:32
  • OfStack

Java USES poi to import data from a database into Excel

Effect:

(link: http://www.blogjava.net/images/blogjava_net/fl1429/WindowsLiveWriter/9f4f65c065eb_FB0E/image_2.png)

When using, import the poi package into the path of the project first. Note that you only need to import the poi package, and then download three jars

Core code:

Connect to database: dbconnection.java


package org.xg.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBConnection {
private final String DBUrl ="jdbc:mysql://localhost:3306/notebook" ;
private final String DBDriver ="com.mysql.jdbc.Driver" ;
private final String username ="root" ;
private final String password ="riskfitfeng" ;
private Connection con ;
public DBConnection()
{
try {
Class.forName(DBDriver) ;
con = DriverManager.getConnection(DBUrl,username,password) ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Connection getDB()
{
return con ;
}
public void closeDb(ResultSet rs,PreparedStatement ps)
{
if(rs!=null)
{
try {
rs.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block

e.printStackTrace();
}
}
if(ps!=null)
{
try {
ps.close() ;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
 The import excel class :MySql2Excel.java
package org.xg.db;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class MySql2Excel {
public MySql2Excel() throws Exception
{
Connection con = null ;
DBConnection db = new DBConnection() ;
con = db.getDB() ;
String sql ="select * from students" ;
ResultSet rs = con.createStatement().executeQuery(sql) ;
//Gets the total number of columns
int CountColumnNum = rs.getMetaData().getColumnCount() ;
int i =1 ;
//Creating Excel documents
HSSFWorkbook wb = new HSSFWorkbook() ;
//Sheet corresponds to a working page
HSSFSheet sheet = wb.createSheet("student Table data ") ;
HSSFRow firstrow = sheet.createRow(0); //The row with index 0 starts
HSSFCell[] firstcell = new HSSFCell[CountColumnNum];
String[] names = new String[CountColumnNum];
names[0] ="ID";
names[1] =" Student id ";
names[2] =" The name ";
names[3] =" gender ";
names[4] =" The class ";
for(int j= 0 ;j<CountColumnNum; j++){
firstcell[j] = firstrow.createCell((short)j);
firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
}
while(rs.next())
{
//Create a row in the spreadsheet
HSSFRow row = sheet.createRow(i) ; //The row subscript 1 starts
for(int j=0;j<CountColumnNum;j++)
{
//Loop in a row
HSSFCell cell = row.createCell((short) j) ;
//Set the encoding set of the table so that Chinese is supported
////Determine the data type in the database first
//Put the values from the result set into the spreadsheet
cell.setCellValue(new HSSFRichTextString(rs.getString(j+1))) ;
}
i++ ;
}
//Create a file output stream and prepare the output spreadsheet
OutputStream out = new FileOutputStream("E:\person.xls") ;
wb.write(out) ;
out.close() ;
System.out.println(" Database export successful ") ;
rs.close() ;
con.close() ;
}
public static void main(String[] args)
{
try {
@SuppressWarnings("unused")
MySql2Excel excel = new MySql2Excel() ;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


For example, you can call this in the front-end JSP:

< A href="ReportServlet" onclick="return confirm(' confirm data export to E:/ down? ');" > Export data to Excel< / a>

The background servlet writes the above code, and notice that the response.sendredirect ("") is needed to return to the front end


Related articles: