Ver Fonte

上传文件至 'POI'

1801010401 há 5 anos atrás
pai
commit
7930a6d29b
4 ficheiros alterados com 263 adições e 0 exclusões
  1. 50 0
      POI/DBConnection.java
  2. 58 0
      POI/ExcelFromDB.java
  3. 73 0
      POI/ExcelOutDB.java
  4. 82 0
      POI/PdfFromDB.java

+ 50 - 0
POI/DBConnection.java

@@ -0,0 +1,50 @@
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+public class DBConnection {
+private final String Url ="jdbc:mysql://localhost:3306/edu" ;
+private final String Driver ="com.mysql.jdbc.Driver" ;
+private final String user ="root" ;
+private final String password ="1009" ;
+private Connection con ;
+public DBConnection()
+{
+try {
+Class.forName(Driver) ;
+con = DriverManager.getConnection(Url,user,password) ;
+} catch (Exception e) {
+// TODO Auto-generated catch block
+e.printStackTrace();
+}
+}
+public Connection getDB()
+{
+return con ;
+}
+public void closeDb(ResultSet rs,PreparedStatement ps)
+{
+if(rs!=null)
+{
+try {
+rs.close() ;
+} catch (SQLException e) {
+// TODO Auto-generated catch block
+
+
+e.printStackTrace();
+}
+}
+if(ps!=null)
+{
+try {
+ps.close() ;
+} catch (SQLException e) {
+// TODO Auto-generated catch block
+e.printStackTrace();
+}
+}
+}
+}

+ 58 - 0
POI/ExcelFromDB.java

@@ -0,0 +1,58 @@
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import org.apache.poi.hssf.usermodel.HSSFCell;
+import org.apache.poi.hssf.usermodel.HSSFRichTextString;
+import org.apache.poi.hssf.usermodel.HSSFRow;
+import org.apache.poi.hssf.usermodel.HSSFSheet;
+import org.apache.poi.hssf.usermodel.HSSFWorkbook;
+
+
+public class ExcelFromDB {
+	public static void main(String[] args) throws Exception{
+    Connection con = null ;      
+    DBConnection db = new DBConnection();  
+    con = db.getDB();  
+    
+    String sql ="select * from student";
+    ResultSet rs = con.createStatement().executeQuery(sql);
+    int CountColumnNum = rs.getMetaData().getColumnCount(); //获取总列数
+
+    HSSFWorkbook wb = new HSSFWorkbook();                   //得到Excel工作簿对象( 创建Excel文档)
+    HSSFSheet sheet = wb.createSheet("student表中的数据");      //得到Excel工作表对象
+    HSSFRow firstrow = sheet.createRow(0);                  //创建表格中的第一行,下标为0
+    HSSFCell[] firstcell = new HSSFCell[CountColumnNum];    //创建单元格
+    String[] names = new String[CountColumnNum];
+    names[0] ="user";
+    names[1] ="name";
+    names[2] ="password";
+    names[3] ="sex";
+    names[4] ="national";
+    names[5]="telephone";
+    names[6]="age";
+    //给第一行的单元格赋值,即表头
+    for(int j= 0;j<CountColumnNum;j++) {
+        firstcell[j] = firstrow.createCell((short)j);
+        firstcell[j].setCellValue(new HSSFRichTextString(names[j]));
+}
+    int i =1;
+    while(rs.next()){  	
+       //创建表格的一行
+       HSSFRow row = sheet.createRow(i);                //下标为1的行开始
+       for(int j=0;j<CountColumnNum;j++){
+       HSSFCell cell = row.createCell((short) j);       //在一行内循环
+       //将结果集里的值放入表格中
+       cell.setCellValue(new HSSFRichTextString(rs.getString(j+1)));}
+       i++;
+}
+//创建文件输出流输出表格
+OutputStream out = new FileOutputStream("C:\\Users\\ASUS\\Desktop\\student.xls");
+wb.write(out);
+out.close();
+System.out.println("数据库导出成功") ;
+rs.close();
+con.close();
+}
+
+}

+ 73 - 0
POI/ExcelOutDB.java

@@ -0,0 +1,73 @@
+
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+
+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;
+ 
+public class ExcelOutDB {	
+public static void main(String[] args) throws Exception {
+    //文件流指向excel文件
+    FileInputStream fin=new FileInputStream("C:\\Users\\ASUS\\Desktop\\stu.xls");
+	try {
+		HSSFWorkbook workbook = new HSSFWorkbook(fin);
+		 HSSFSheet sheet=workbook.getSheetAt(0);   //得到工作表
+		    HSSFRow row=null;                      //对应excel的行
+		    HSSFCell cell=null;                    //对应excel的列
+		    int totalRow=sheet.getLastRowNum();    //得到excel的总记录条数
+		 
+		    String user="";
+		    String name="";
+		    String password="";
+		    String sex="";
+		    String national="";
+		    String telephone="";
+		    String age="";
+		    
+		    Connection con = null;       //数据库连接
+			 DBConnection db = new DBConnection();  
+			 con = db.getDB();  
+		    String sql="insert into student(user,name,password,sex,national,telephone,age) values(?,?,?,?,?,?,?)";
+		    
+		    //利用循环把数据导入数据库中
+		    for(int i=1;i<=totalRow;i++){
+		     row=sheet.getRow(i);
+		     cell=row.getCell((short) 0);
+		     user=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 1);
+		     name=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 2);
+		     password=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 3);
+		     sex=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 4);
+		     national=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 5);
+		     telephone=cell.getRichStringCellValue().toString();
+		     cell=row.getCell((short) 6);
+		     
+		     
+		     PreparedStatement pst=con.prepareStatement(sql);
+		     pst.setString(1,user);
+		     pst.setString(2,name);
+		     pst.setString(3,password);
+		     pst.setString(4,sex);
+		     pst.setString(5,national);
+		     pst.setString(6,telephone);
+		     pst.setString(7,age);		     
+		     pst.execute();		     
+		    }
+		    System.out.println("导入成功");
+		       
+	} catch (IOException e) {
+		// TODO 自动生成的 catch 块
+		e.printStackTrace();
+	}
+   
+}    
+   
+}

+ 82 - 0
POI/PdfFromDB.java

@@ -0,0 +1,82 @@
+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 com.itextpdf.text.BaseColor;
+import com.itextpdf.text.Document;
+import com.itextpdf.text.Element;
+import com.itextpdf.text.Font;
+import com.itextpdf.text.PageSize;
+import com.itextpdf.text.Paragraph;
+import com.itextpdf.text.pdf.BaseFont;
+import com.itextpdf.text.pdf.PdfPTable;
+import com.itextpdf.text.pdf.PdfWriter;
+ 
+public class PdfFromDB {	
+	//数据表的字段数
+	private static final int colNum = 7;
+	//设置表格的属性
+	private static final int spacing = 1;
+	private static final int padding = 2;
+
+	public static void main(String[] args) throws Exception {	
+		//支持中文
+		BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); 
+        Font fontChinese =new Font(baseFontChinese,12,Font.NORMAL); 
+        //定义一个文档对象
+		Document document = new Document(PageSize.A4.rotate(),10,10,10,10);
+		//连接数据库
+		Connection conn = null;
+		DBConnection db = new DBConnection();  
+		conn = db.getDB();
+		
+		try {
+			//在文档中创建一个PDF文件
+			PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\ASUS\\Desktop\\student.pdf"));
+			document.open();    
+			//设置有几列
+			PdfPTable table = new PdfPTable(colNum);
+			//设置字段单元格的相对大小
+			int[] cellsWidth = {6,5,5,2,3,8,2};
+			table.setWidths(cellsWidth);
+			//设置表格占文档的大小比例
+			table.setWidthPercentage(90);
+			table.getDefaultCell().setPadding(padding);
+			table.getDefaultCell().setBorderWidth(spacing);
+			//设置单元格文本居中
+			table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
+			//查询语句
+			String sql = "select * from student";
+			//执行查询语句
+			PreparedStatement ps = conn.prepareStatement(sql);
+			//获取结果集
+			ResultSet rs = ps.executeQuery();
+			//获取表格的字段描述信息
+			ResultSetMetaData metaData = rs.getMetaData();
+			//添加字段
+			for(int i=0;i<colNum;i++){
+				//获取字段名
+				table.addCell(new Paragraph(metaData.getColumnLabel(i+1),fontChinese));
+			}
+			table.setHeaderRows(1);                  //表头设置结束,表示第一行属于表头
+			table.getDefaultCell().setBorderWidth(1);
+			//将查询到的每一条数据作为单独的一行添加到pdf文件中
+			while(rs.next()){
+				for(int i=1;i<=colNum;i++){
+					table.addCell(new Paragraph(rs.getString(i),fontChinese));
+				}
+			}
+			//将表格添加到文档中
+			document.add(table);
+		} catch (Exception e) {
+			e.printStackTrace();
+		} finally {
+			conn.close();
+			document.close();
+			System.out.println("数据输出成功");
+		}
+	}
+
+}