poi解析Excel,遍歷表結構,獲取單元格內容,拼接sql語句,寫入TXT檔案

Walter Sun發表於2018-04-28
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

public class SqlCreate {

    /**
     * @param args
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    private static String path = "F:\\15xsd修改\\03_SMD"; // execl儲存路徑

    private static String savepath = "F:\\15xsd修改\\增量指令碼\\zlsql2.txt"; //拼接後的sql儲存路徑

    public static void main(String[] args) {
        try {
            File file = new File(path); //此處file不是檔案,是路徑
            FileOutputStream out = new FileOutputStream(savepath);
//            OutputStream out = new FileOutputStream(savepath);
            Workbook wb = null;
            int count=0;
            for (File f : file.listFiles()) { //通過".listFiles()"方法遍歷路徑下檔案
                count++;
                System.out.println("獲取檔案:" + f+"----"+count);
                InputStream excelFileInputStream = null;
                excelFileInputStream = new FileInputStream(f);
                wb = WorkbookFactory.create(excelFileInputStream);
                excelFileInputStream.close();
                
                Sheet st = wb.getSheet("TAB");
                Sheet sc = wb.getSheet("COL");

                int stl = st.getLastRowNum();
                int scl = sc.getLastRowNum();

                Row rowst = st.getRow(4);
                Cell cellschema = rowst.getCell(2);
//                System.out.println(cellschema);

                String sql = "";
                for (int i = 0; i < scl; i++) {
                    //                    String sql="";
                    Row row = sc.getRow(i);//獲取Excel的行,下標從0開始
                    if (row == null) {//若行為空,則遍歷下一行
                        continue;
                    }
                    Cell cell = row.getCell(1);//獲取指定單元格,單元格從左到右下標從0開始
                    Cell cell2=row.getCell(0);
                    if (cell != null
                            && cell.getStringCellValue().equals("C_DJHKYKWDCL")) {
//                        sql += "ALTER TABLE " + cellschema + "."+cell2
//                        + " RENAME N_DJHKYKWDCL TO C_DJHKYKWDCL;"+"\n" ;
                        sql += "ALTER TABLE " + cellschema + "."+cell2
                                + " ALTER C_DJHKYKWDCL TYPE TEXT;"+"\n" ;
                        System.out.println(sql);
                        byte[]a = sql.getBytes();
                        out.write(a);
                    }
                }
            }

            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

相關文章