zsh_root
2024-01-02 7b595546af704983dbafcd0d385c8768ddacefc2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package PbuliClass;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.sql.ResultSet;
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 DataBase.DatabaseManagement;
//Êý¾ÝתEXcelÊä³ö
public class dataToExcel {
    
    ResultSet rs;//½á¹û¼¯¶ÔÏó
 
    public  void toExcel( String sql, String outName,String sheetName) throws Exception {
        rs=DatabaseManagement.findForResultSet(sql);//Êý¾Ý¿â²éѯ        
        HSSFWorkbook wb = new HSSFWorkbook();//´´½¨excel¶ÔÏó
        HSSFSheet sheet =wb.createSheet(sheetName);//´´½¨excel±íµ¥
        HSSFRow row = sheet.createRow(0);//±íµ¥ÐжÔÏó
        HSSFCell cell;//±íµ¥ÁжÔÏó
        //ÎļþÍ·ÄÚÈÝÒ²¾ÍÊǵÚ0ÐеÄÖµ
        for (int j = 0; j < rs.getMetaData().getColumnCount(); ++j) {
            String colName = rs.getMetaData().getColumnLabel(+ 1);
            cell = row.createCell(j);
            cell.setCellValue(colName);//ÉèÖõ¥Ôª¸ñµÄÖµ
        }
        int i = 0;
        while (rs.next()) {
            row = sheet.createRow(+ 1);
            for (int j = 0; j < rs.getMetaData().getColumnCount(); ++j) {
                String c = rs.getString(+ 1);
                row.createCell(j).setCellValue(c);
            }
            ++i;
        }
        
        FileOutputStream output = new FileOutputStream(outName);//×Ö½ÚÊä³öÁ÷
        BufferedOutputStream buffOutput=new BufferedOutputStream(output,1024);//»º³å×Ö½ÚÊä³öÁ÷
        wb.write(buffOutput);
        output.flush();//Ë¢ÐÂ
        buffOutput.close();//¹Ø±ÕÁ÷
        output.close();//¹Ø±ÕÁ÷
        wb.close();//¹Ø±ÕÁ÷
        rs.close();  //¹Ø±ÕÁ÷      
    }
    
 
}