2013年11月11日 星期一

java-mysql-csv-template

import java.sql.*;
import java.net.*;
import java.io.*;
import java.util.*;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
public class BankCSV {
public static String padL(String s, int n,char t) {
return String.format("%1$" + n + "s", s).replace(' ', t);
}
public static String padR(String s, int n,char t) {
return String.format("%1$-" + n + "s", s).substring(0, n).replace(' ', t);
    }
public static void main( String argv[] ) {
go();
}
public static void go(){
String mCompanyName="";
String mAddress1="";
String mIRFileNumber="";
String mDesignation="";
FileOutputStream fop = null;
File file;
String content = "This is the text content";
Calendar cal0 = Calendar.getInstance();
int Year = cal0.get(Calendar.YEAR);
int Month = cal0.get(Calendar.MONTH)+1;
int Day = cal0.get(Calendar.DAY_OF_MONTH);
try{
file = new File("/hr/newfile.txt");
fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
  String result="";
ResultSet rs = null;
Connection con = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/DataBaseName?useUnicode=true&characterEncoding=UTF8","UserID", "UserPassword");
stmt = con.createStatement();
ResultSet rs0 = null;
Statement stmt0 = null;
stmt0 = con.createStatement();
String sqlString="";
String _HEADERS="surname,year,mth,departmentName,banker,bankerno,netpay";
String _FIELDS="if(isnull(surname),'',surname),if(isnull(year),'',year),if(isnull(mth),'',mth),if(isnull(departmentName),'',departmentName)";
_FIELDS=_FIELDS+",if(isnull(banker),'',banker),if(isnull(bankerno),'',bankerno),if(isnull(netpay),'',netpay)";
String _FORMATS=  "S,S,S,S,S,S,S";
String header[]=_HEADERS.split(",");
String format[]=_FORMATS.split(",");
sqlString="select "+_FIELDS+"from payroll where bankstatus='B'";
//System.out.println(sqlString);
rs = stmt.executeQuery(sqlString);
String batchHeader="";
String cMonth= padL(Integer.toString(Month).trim(),2,'0');
String cDay= padL(Integer.toString(Day).trim(),2,'0');
byte[] contentInBytesH = batchHeader.getBytes();
fop.write(contentInBytesH);
fop.flush();
String sw="";
String delimiter="";
int i0=format.length;
for (int rr=1;rr<=format.length;rr++){
sw=sw+delimiter+header[rr-1];
System.out.print(header[rr-1]);
delimiter=",";
}
System.out.print("\n");
sw=sw+"\r\n";
while (rs.next()){
delimiter="";
for (int rr=1;rr<=format.length;rr++){
String s = rs.getString(rr);
sw=sw+delimiter+s;
System.out.print(delimiter);
System.out.print(s);
delimiter=",";
}
System.out.print("\n");
sw=sw+"\r\n";
}
byte[] contentInBytes = sw.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}

沒有留言:

張貼留言