62,614
社区成员
发帖
与我相关
我的任务
分享
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
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;
//将数据库的数据导出到Excel
public class Test {
/*****可修改部分start******/
//导出的表名
public static String tables="demo";
//sql语句
public static String sqls="select top 500 * from (select dh.dh_org_id, dh.dh_carrier_id, dh.chengyunshangdanhao, dh.billid as dhbillid, dh.dh_dispatch_no, dh.dh_truck_license_no, dh_primary_driver, dh.dh_primary_tel, dh.peisongzurenyuan, dh.lianxidianhua, dh.cheliangleixing as dh_cheliangleixing, dh.dh_dispatch_datetime, DH_DEPART_DATETIme, dh.yujiwanchengshijian as dh_yujiwanchengshijian, dh.dh_start_area_id, dh.dh_end_area_id, dh.yunshufangshi_2 as dh_yunshufangshi, dh.yunzuofangshi, dh.DH_TRAILER_LICENSE_NO, dh.status as dhstatus, clh_consign_header_id, clh_logistics_no, clh_logistics_header_id, clh_consign_no, clh_consign_datetime , clh.billid as clhbillid, clh_cargo_load_no, clh.kehuyaoqiuwanchengshijian as clh_kehuyaoqiuwanchengshijian, clh_consigner_id, clh_consigner_no, clh_emergency_degree_id, clh_settle_method_id, clh.kehu as clh_kehu, clh.kehudanhao as clh_kehudanhao, clh_load_address, clh_load_area_id, clh_unload_area_id, CLH_UNLOAD_CONTACT, CLH_UNLOAD_UNIT_NAME, clh_unload_address, clh.tuopanshu as clh_tuopanshu, clh_total_packs, clh_total_cubage, clh_total_gross_weight, clh.zhuyaowuliaoleibie as clh_zhuyaowuliaoleibie, clh.status as clhstatus, clt.cltl_trace_datetime as trace_datetime, clt.cltl_location as location, clt.cltl_speed as speed, convert(varchar(50), CLH_DEPART_DATETIME) + '..到达..' + (select name from cp_area a where a.id = clh_load_area_id) + '..正在....从.' + (select name from cp_area a where a.id = clh_load_area_id) + ' .>>>.' + (select name from cp_area a where a.id = clh_unload_area_id) as trace_remark, 1 as shifoukejian, '在途..CL' as info_flag from tm_dispatch_cargo_load_l dcll inner join tm_dispatch_h dh on dcll.billid = dh.billid right outer join tm_cargo_load_h clh on dcll.dcll_cargo_load_header_id = clh.billid inner join tm_cargo_load_trace_l clt on clh.billid=clt.billid where clh.status = 84 union all select dh.dh_org_id, dh.dh_carrier_id, dh.chengyunshangdanhao, dh.billid as dhbillid, dh.dh_dispatch_no, dh.dh_truck_license_no, dh_primary_driver, dh.dh_primary_tel, dh.peisongzurenyuan, dh.lianxidianhua, dh.cheliangleixing as dh_cheliangleixing, dh.dh_dispatch_datetime, DH_DEPART_DATETIme, dh.yujiwanchengshijian as dh_yujiwanchengshijian, dh.dh_start_area_id, dh.dh_end_area_id, dh.yunshufangshi_2 as dh_yunshufangshi, dh.yunzuofangshi, DH_TRAILER_LICENSE_NO, dh.status as dhstatus, clh_consign_header_id, clh_logistics_no, clh_logistics_header_id, clh_consign_no, clh_consign_datetime , clh.billid as clhbillid, clh_cargo_load_no, clh.kehuyaoqiuwanchengshijian as clh_kehuyaoqiuwanchengshijian, clh_consigner_id, clh_consigner_no, clh_emergency_degree_id, clh_settle_method_id, clh.kehu as clh_kehu, clh.kehudanhao as clh_kehudanhao, clh_load_address, clh_load_area_id, clh_unload_area_id, CLH_UNLOAD_CONTACT, CLH_UNLOAD_UNIT_NAME, clh_unload_address, clh.tuopanshu as clh_tuopanshu, clh_total_packs, clh_total_cubage, clh_total_gross_weight, clh.zhuyaowuliaoleibie as clh_zhuyaowuliaoleibie, clh.status as clhstatus, cls.dtl_trace_datetime , cls.dtl_location, cls.dtl_speed, convert(varchar(50), CLH_DEPART_DATETIME) + '..到达..' + (select name from cp_area a where a.id = clh_load_area_id) + '..正在....从.' + (select name from cp_area a where a.id = clh_load_area_id) + ' .>>>.' + (select name from cp_area a where a.id = clh_unload_area_id) as trace_remark, 1 as shifoukejian, '在途..DH' as info_flag from tm_dispatch_cargo_load_l dcll inner join tm_dispatch_h dh on dcll.billid = dh.billid right outer join tm_cargo_load_h clh on dcll.dcll_cargo_load_header_id = clh.billid inner join tm_dispatch_trace_l cls on dcll.billid=cls.billid where not exists(select * from tm_cargo_load_trace_l a where a.billid = clh.billid) and clh.status = 84 union all select dh.dh_org_id, dh.dh_carrier_id, dh.chengyunshangdanhao, dh.billid as dhbillid, dh.dh_dispatch_no, dh.dh_truck_license_no, dh_primary_driver, dh.dh_primary_tel, dh.peisongzurenyuan, dh.lianxidianhua, dh.cheliangleixing as dh_cheliangleixing, dh.dh_dispatch_datetime, DH_DEPART_DATETIme, dh.yujiwanchengshijian as dh_yujiwanchengshijian, dh.dh_start_area_id, dh.dh_end_area_id, dh.yunshufangshi_2 as dh_yunshufangshi, dh.yunzuofangshi, DH_TRAILER_LICENSE_NO, dh.status as dhstatus, clh_consign_header_id, clh_logistics_no, clh_logistics_header_id, clh_consign_no, clh_consign_datetime , clh.billid as clhbillid, clh_cargo_load_no, clh.kehuyaoqiuwanchengshijian as clh_kehuyaoqiuwanchengshijian, clh_consigner_id, clh_consigner_no, clh_emergency_degree_id, clh_settle_method_id, clh.kehu as clh_kehu, clh.kehudanhao as clh_kehudanhao, clh_load_address, clh_load_area_id, clh_unload_area_id, CLH_UNLOAD_CONTACT, CLH_UNLOAD_UNIT_NAME, clh_unload_address, clh.tuopanshu as clh_tuopanshu, clh_total_packs, clh_total_cubage, clh_total_gross_weight, clh.zhuyaowuliaoleibie as clh_zhuyaowuliaoleibie, clh.status as clhstatus, CLH_DEPART_DATETIME as trace_datetime , '途中...' as location, 0 as speed, convert(varchar(50), CLH_DEPART_DATETIME) + '..到达..' + (select name from cp_area a where a.id = clh_load_area_id) + '..正在....从.' + (select name from cp_area a where a.id = clh_load_area_id) + ' .>>>.' + (select name from cp_area a where a.id = clh_unload_area_id) as trace_remark, 1 as shifoukejian, '在途..AL' as info_flag from tm_dispatch_cargo_load_l dcll inner join tm_dispatch_h dh on dcll.billid = dh.billid right outer join tm_cargo_load_h clh on dcll.dcll_cargo_load_header_id = clh.billid where not exists(select * from tm_cargo_load_trace_l a where a.billid = clh.billid) and not exists(select * from tm_dispatch_trace_l a where a.billid = dcll.billid) and clh.status = 84)a";
//导出表的csv文件保存的地址
public static String outputFile="D:/beiye.xls";
//数据库
public static String url = "jdbc:sqlserver://127.0.0.1;database=boyolsys;";
public static String username = "sa";
public static String password = "111111";
/*****可修改部分 end******/
public static String driver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
public static Connection con = null;
public static void main(String[] args){
try {
Class.forName(driver);
con = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException classE) {
classE.printStackTrace();
} catch (SQLException sqlE) {
sqlE.printStackTrace();
}
outPutTable();
}
/**
* 功能描述:把数据库中的表导出,生成csv文件
* @return
* @ 2016-9-8
*/
public static void outPutTable(){
long a=System.currentTimeMillis();
PreparedStatement ps_struts = null;
ResultSet rs_struts = null;
try{
HSSFWorkbook workbook = new HSSFWorkbook();
String[] tempo ;
int rowNum=1;
try {
ps_struts=con.prepareStatement(sqls);
rs_struts = ps_struts.executeQuery();
ResultSetMetaData rsm = rs_struts.getMetaData();
HSSFSheet sheet = workbook.createSheet(tables);
int columnCount = rsm.getColumnCount();
try{
HSSFRow row1 = sheet.createRow(0);
for (int i = 1; i <=columnCount; i++) {
sheet.autoSizeColumn(i);
String columnName=rsm.getColumnName(i);
HSSFCell cell1 = row1.createCell(i-1);
cell1.setCellValue(columnName);
}
/*FileOutputStream fOut = new FileOutputStream(outputFile);
workbook.write(fOut);
fOut.flush();
fOut.close();*/
}catch(Exception e) {
System.out.println("已运行 outPutTable (): " + e );
}
while(rs_struts.next()){
HSSFRow row = sheet.createRow(rowNum);
tempo = new String[columnCount];
for (int i = 0; i <columnCount; i++) {
HSSFCell cell = row.createCell(i);
sheet.autoSizeColumn(i);
String columnName=rs_struts.getMetaData().getColumnName(i+1);
tempo[i] = rs_struts.getString(columnName);
cell.setCellValue(tempo[i]);
}
tempo = null;
rowNum++;
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
FileOutputStream fOut = new FileOutputStream(outputFile);
workbook.write(fOut);
fOut.flush();
fOut.close();
}catch(Exception e) {
System.out.println("已运行 outPutTable (): " + e );
}
System.out.println( "-----------------表开始导出完成!-------------------");
System.out.println("耗时:"+(System.currentTimeMillis()-a)/1000f+"秒");
}
}
/**
* 功能描述:把数据库中的表导出,生成csv文件
*
* @return
* @ 2016-9-8
*/
public void outPutTable() {
long a = System.currentTimeMillis();
Connection con = null;
PreparedStatement ps_struts = null;
ResultSet rs_struts = null;
int rowNum = 1;
try {
HSSFWorkbook workbook = new HSSFWorkbook();
con = dataSource.getConnection();
ps_struts = con.prepareStatement("select * from t_item limit 65535");
rs_struts = ps_struts.executeQuery();
ResultSetMetaData rsm = rs_struts.getMetaData();
HSSFSheet sheet = workbook.createSheet("sheet1");
int columnCount = rsm.getColumnCount();
int[] cell_size = new int[columnCount];
int[] max_row = new int[columnCount];
HSSFRow row1 = sheet.createRow(0);
for (int i = 1; i <= columnCount; i++) {
String columnName = rsm.getColumnName(i);
cell_size[i-1] = columnName.getBytes().length;
max_row[i-1] = 0;
HSSFCell cell1 = row1.createCell(i - 1);
cell1.setCellValue(columnName);
}
while (rs_struts.next()) {
HSSFRow row = sheet.createRow(rowNum);
for (int i = 0; i < columnCount; i++) {
HSSFCell cell = row.createCell(i);
// 这三句非常耗时间, 尤其是autoSizeColumn不应该在这里调用
// 上面的列是按序取的, 下面的结果按序取就一一对应了没有必要先取name再根据name取值
// sheet.autoSizeColumn(i);
// String columnName=rs_struts.getMetaData().getColumnName(i+1);
// tempo[i] = rs_struts.getString(columnName);
String value = rs_struts.getString(i + 1);
int byte_len = value.getBytes().length;
if (byte_len > cell_size[i]) {
cell_size[i] = byte_len;
max_row[i] = rowNum;
}
cell.setCellValue(value);
}
rowNum++;
}
resize(sheet, max_row);
FileOutputStream fOut = new FileOutputStream("f:/temp/t_item.xls");
workbook.write(fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
System.out.println("已运行 outPutTable (): " + e);
} finally {
if (rs_struts != null) {
try {
rs_struts.close();
} catch (SQLException e) {
}
}
if (ps_struts != null) {
try {
ps_struts.close();
} catch (SQLException e) {
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
}
}
}
System.out.println("-----------------表开始导出完成!-------------------");
System.out.println("共计" + (rowNum-1) +"行数据,耗时:" + (System.currentTimeMillis() - a) + "毫秒");
}
private static final char defaultChar = '0';
private static final FontRenderContext fontRenderContext = new FontRenderContext(null, true, true);
void resize(Sheet sheet, int[] max_row) {
resize(sheet, false, max_row);
}
void resize(Sheet sheet, boolean useMergedCells, int[] max_row) {
AttributedString str;
TextLayout layout;
Workbook wb = sheet.getWorkbook();
DataFormatter formatter = new DataFormatter();
Font defaultFont = wb.getFontAt((short) 0);
str = new AttributedString(String.valueOf(defaultChar));
copyAttributes(defaultFont, str, 0, 1);
layout = new TextLayout(str.getIterator(), fontRenderContext);
int defaultCharWidth = (int)layout.getAdvance();
for (int i = 0; i < max_row.length; i++) {
Cell cell = sheet.getRow(max_row[i]).getCell(i);
double width = SheetUtil.getCellWidth(cell, defaultCharWidth, formatter, useMergedCells);
if (width != -1) {
width *= 256;
int maxColumnWidth = 255 * 256;
if (width > maxColumnWidth) {
width = maxColumnWidth;
}
}
sheet.setColumnWidth(i, (int) width);
}
}
private static void copyAttributes(Font font, AttributedString str, int startIdx, int endIdx) {
str.addAttribute(TextAttribute.FAMILY, font.getFontName(), startIdx, endIdx);
str.addAttribute(TextAttribute.SIZE, (float)font.getFontHeightInPoints());
if (font.getBoldweight() == Font.BOLDWEIGHT_BOLD) str.addAttribute(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD, startIdx, endIdx);
if (font.getItalic() ) str.addAttribute(TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE, startIdx, endIdx);
if (font.getUnderline() == Font.U_SINGLE ) str.addAttribute(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON, startIdx, endIdx);
}
mysql> select count(1) from t_item;
+----------+
| count(1) |
+----------+
| 500000 |
+----------+
1 row in set (1.50 sec)