import jxl.*; import jxl.write.*;i mport java.io.*; public class CleanExcel { public static void clean(String inFile, String outFile){ //首先需要声明输入输出流与Workbook,Workbook对应Excel文件 InputStream is = null; Workbook inWb = null; OutputStream os = null; WritableWorkbook outWb = null; try{ //实例化输入输出流与Workbook is = new FileInputStream(inFile); //Workbook无法通过new关键字进行实例化,必须调用Workbook.getWorkbook(File)静态方法 inWb = Workbook.getWorkbook(is); os = new FileOutputStream(outFile); outWb = Workbook.createWorkbook(os); //下面这一句是选择原文件的工作表,Sheet对应的是Excel中的Sheet Sheet inSheet = inWb.getSheet("Sheet1"); //WritableSheet为要创建的文件中的工作表 WritableSheet outSheet = outWb.createSheet("Sheet1", 0); //设置循环标志 boolean flag = true; //循环条件 int i = 0; while(flag){ //Cell对应一个单元格,getCell方法第一个参数对应列,第二个参数对应行。 //注意:行和列的开始坐标均为0,与JAVA中的数组一样 Cell tmp = inSheet.getCell(0, i); //取得每行第一列单元格中的数据。不管单元格中的数据在EXCEL中为何种类型,读取之后都将成为String类型 String c = tmp.getContents().trim(); //为处理方面,EXCEL文件中最后一行的第一个单元格设置了一个break标志,读到这一行时将退出循环 if(c.equals("break")){ flag = false; break; } //我处理的EXCEL表格为8列 for(int j = 0; j < 8; j++){ //取得源单元格 Cell inCell = inSheet.getCell(j, i); //获取数据 String content = inCell.getContents().trim(); //创建新单元格,并用数据填充 Label labelCF=new Label(j, i, content); //将新单元格加入到新工作表中 outSheet.addCell(labelCF); } i++; } //写入文件 outWb.write(); //关闭流 outWb.close(); os.close(); }catch(Exception e){ e.printStackTrace(); } } //测试 public static void main(String[] args){ try { String in = "old.xls"; String out = "new.xls"; CleanExcel.clean(in, out); } catch (Exception e) { e.printStackTrace(); } } }
例子2-----》利用jxl包来完成excel导入导出
import java.io.File; import java.io.IOException; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; public class ExcelTest { public static void main(String[] adf) { try { Workbook workbook = Workbook .getWorkbook(new File( "d://myfile.xls")); Sheet sheet = workbook.getSheet(0); String[] tempValue = new String[sheet.getColumns()]; for (int i = 0; i < sheet.getRows(); i++) { for (int j = 0; j < sheet.getColumns(); j++) { String value = sheet.getCell(j, i).getContents(); if (value.equals( " ")) value = tempValue[j]; System.out.print(value + "/t/t/t/t/t/t/t "); tempValue[j] = value; } System.out.println( " "); } } catch (BiffException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
例子3-----》利用apache包来完成excel导入导出
import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; 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 org.apache.poi.poifs.filesystem.POIFSFileSystem; public class POITest { private static Connection conn = null; private static Statement stmt = null; private static boolean connectDB2() { String url = ""; String username = "username"; String password = "password"; //加载驱动程序以连接数据库 try { //添加类库驱动包db2jcc.jar和db2jcc_license_cu.jar Class.forName("com.ibm.db2.jcc.DB2Driver"); url = "jdbc:db2://192.168.0.1:50000/dbname"; //添加类库驱动包db2java.jar //Class.forName("com.ibm.db2.jdbc.app.DB2Driver").newInstance(); //url = "jdbc:db2:njtcdata"; conn = DriverManager.getConnection(url, username, password); stmt = conn.createStatement(); } //捕获加载驱动程序异常 catch (ClassNotFoundException cnfex) { System.err.println("装载JDBC驱动程序失败。"); cnfex.printStackTrace(); return false; } //捕获连接数据库异常 catch (SQLException sqlex) { System.err.println("无法连接数据库"); sqlex.printStackTrace(); //System.exit(1); // terminate program return false; } return true; } private static boolean readExcelToDB2() { POIFSFileSystem fs = null; HSSFWorkbook wb = null; try { fs = new POIFSFileSystem(new FileInputStream("c://test.xls")); wb = new HSSFWorkbook(fs); } catch (IOException e) { e.printStackTrace(); return false; } HSSFSheet sheet = wb.getSheetAt(0); HSSFRow row = null; HSSFCell cell = null; String name = ""; int id = 0; int rowNum, cellNum; int i; rowNum = sheet.getLastRowNum(); for (i = 0; i <= rowNum; i++) { row = sheet.getRow(i); //cellNum = row.getLastCellNum(); cell = row.getCell((short) 0); name = cell.getStringCellValue(); cell = row.getCell((short) 1); id = (int) cell.getNumericCellValue(); String sql = "insert into TEST(ID, NAME) values(" + id + ",'" + name + "')"; try { stmt.executeUpdate(sql); } catch (SQLException e1) { e1.printStackTrace(); return false; } } return true; } public static void main(String[] args) { if (connectDB2()==true){ if (readExcelToDB2()==true) System.out.println("数据导入成功"); else System.out.println("数据导入失败"); } else{ System.out.println("数据库连接失败"); } } }
例子4-----》文本文件导入例子
1、将数据按一定规律录入到一个文本文件,每一行代表一条记录。
下面是数据库建表SQL:
CREATE TABLE t_FltPsgInfo -- 航班乘客信息
(
FltNum VARCHAR(10), -- 航班号
FltLine VARCHAR(30), -- 航线
FltDate VARCHAR(10), -- 日期
PsgName VARCHAR(30), -- 姓名
PsgType VARCHAR(30), -- 乘客类型,数字表示,目前是1-13
PsgSex VARCHAR(1), -- 0 男 1 女
PsgCab VARCHAR(1), -- 几等舱, F/Y 舱位按字母顺序排列
PsgSeatNo VARCHAR(5),-- 座位号 2A,22F,根据这个得到一排有多少个座位,共有多少排座位信息
PsgInfo VARCHAR(2048) -- 详细信息,可能很长
)
我们将向表t_FltPsgInfo中插入1000条记录。
新建一个文本文件,每一行代表一条记录,如:
HU7804,广州-北京,2007-07-18,谢丽珍,3,1,C,3A,服务保障信息:未用餐随行人员…
其中以“,”作为字段的分隔标志,我们在解析这个文本文件时将根据“,”来拆分字段值。
按照上面的格式,将要插入的数据输入到文本文件中,注意,是每一行代表一条记录,或者你已有从数据库导出的文本文件,那你就只需找到文件的规律,稍作调整就行了。
2、编写Java源码
1》数据库操作类InsertDB.java
package test; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class Ins ertDB { private static final String user = "sa"; private static final String pwd = "sa"; private static final String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=hhfly"; private static final String driver = "com.microsoft.jdbc.sqlserver.SQLServerDriver"; public static Connection getCon() { Connection con = null; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url, user, pwd); if (con != null) { System.out.println("你已连接到数据库:" +con.getCatalog()); } } catch (Exception e) { System.out.println("连接数据库失败!"); e.printStackTrace(); } return con; } public boolean insertDB(String FltNum, String FltLine, String FltDate, String PsgName, String PsgType, String PsgSex, String PsgCab,String PsgSeatNo, String PsgInfo) { Connection con = null; Statement stm = null; boolean flag = false; String sql = "insert into t_FltPsgInfo values('" + FltNum + "','" + FltLine + "','" + FltDate + "','" + PsgName + "','" + PsgType + "','" + PsgSex + "','" + PsgCab + "','" + PsgSeatNo + "','"+ PsgInfo + "')"; try { con = getCon(); stm = con.createStatement(); int i = stm.executeUpdate(sql); if (i > 0) { flag = true; System.out.println(flag + "插入数据成功!"); } } catch (Exception e) { flag = false; e.printStackTrace(); } finally { close(null, stm, con); } return flag; } //关闭相关连接 public void close(ResultSet rs, Statement stm, Connection con) { if (rs != null) try { rs.close(); } catch (Exception e) { ze=3> e.printStackTrace(); } if (stm != null) try { stm.close(); } catch (Exception e) { e.printStackTrace(); } if (con != null) try { con.close(); } catch (Exception e) { e.printStackTrace(); } } }
2》数据采集类DataGather.java
package test; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; public class DataGather { private static final String path = "src/resource/test"; public static final String openFileStyle = "r"; public static final String fieldLimitChar = ","; public static final int fieldAllCount = 9; private int count; private String FltNum; private String FltLine; private String FltDate; private String PsgName; private String PsgType; private String PsgSex; private String PsgCab; private String PsgSeatNo; private String PsgInfo; /* * 功能:解析文本文件 */ public void loadFile() { try { RandomAccessFile raf = new RandomAccessFile(path,openFileStyle); String line_record = raf.readLine(); while (line_record != null) { // 解析每一条记录 parseRecord(line_record); line_record = raf.readLine(); } System.out.println("共有合法的记录" + count + "条"); } catch (Exception e) { e.printStackTrace(); } } /** 功能:具体解析每一条记录,这里可以增加很多对记录的解析判断条件,如是否为字母、 * 数字、email等。 e=3> */ private void parseRecord(String line_record) throws Exception { //拆分记录 String[] fields = line_record.split(fieldLimitChar); if (fields.length == fieldAllCount) { FltNum = tranStr(fields[0]); FltLine = tranStr(fields[1]); FltDate = tranStr(fields[2]); PsgName = tranStr(fields[3]); PsgType = tranStr(fields[4]); PsgSex = tranStr(fields[5]); PsgCab = tranStr(fields[6]); PsgSeatNo = tranStr(fields[7]); PsgInfo = tranStr(fields[8]); System.out.println(FltNum + " " + FltLine + " " + FltDate + " " + PsgName + " " + PsgType + " " + PsgSex + " " + PsgCab + " " + PsgSeatNo + " " + PsgInfo); InsertDB db = new InsertDB(); db.insertDB(FltNum, FltLine, FltDate, PsgName, PsgType, PsgSex, PsgCab, PsgSeatNo, PsgInfo); count++; } } private String tranStr(String oldstr) { String newstr = ""; try { newstr = new String(oldstr.getBytes("ISO-8859-1"), "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return newstr; } }
3》测试类Test.java
package test; public class Test { public static void main(String[] args) { try { DataGather gather = new DataGather (); gather.loadFile(); } catch (Exception e) { e.printStackTrace(); } } }