最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java生成excel報表文件示例

 更新時間:2017年02月16日 14:30:46   作者:一念花開滿天下  
本篇文章主要介紹了java生成excel報表文件示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

此次簡單的操作將數(shù)據(jù)從數(shù)據(jù)庫導(dǎo)出生成excel報表以及將excel數(shù)據(jù)導(dǎo)入數(shù)據(jù)庫

首先建立數(shù)據(jù)庫的連接池:

package jdbc;

import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class BaseDAO {
  private static BasicDataSource ds;
  static{                                         
    try {                                         
      //1.讀取配置文件conf.properties,采用java.util.Properties來讀取           
      Properties p=new Properties();                           
      //2.通過文件流讀取并解析配置文件內(nèi)容,本地數(shù)據(jù)庫用的mysql,所以把配置文件mysql的配置放開,其他數(shù)據(jù)庫配置注釋                        
      p.load(new FileInputStream("src/jdbc.properties"));                  
      String driverName=p.getProperty("jdbc.driverClassName");//獲取驅(qū)動名稱            
      String url=p.getProperty("jdbc.url");//獲取數(shù)據(jù)庫的url                
      String user=p.getProperty("jdbc.username");//用戶名                     
      String password=p.getProperty("jdbc.password");//密碼                  
      int maxActive=Integer.parseInt(p.getProperty("jdbc.maxActive"));//獲取最大連接數(shù)     
      int maxWait=Integer.parseInt(p.getProperty("jdbc.maxWait"));//獲取最大等待時間      
      //3.創(chuàng)建一個連接池                                 
      ds=new BasicDataSource();                              
      ds.setDriverClassName(driverName);//設(shè)置驅(qū)動名稱                  
      ds.setUrl(url);//設(shè)置數(shù)據(jù)庫地址                           
      ds.setUsername(user);//設(shè)置用戶名                          
      ds.setPassword(password);//設(shè)置密碼                         
      ds.setMaxActive(maxActive);//設(shè)置最大連接數(shù)                     
      ds.setMaxWait(maxWait);//設(shè)置最大等待時間                                                                
    } catch (Exception e) {                                
      e.printStackTrace();                                
    }                                           
  }
  
  public static Connection getConnection() throws Exception {
    try {
      return ds.getConnection();
    } catch (Exception e) {
      System.out.println("連接數(shù)據(jù)庫異常");
      throw e;
    }
  }
  
  public static void close(Connection conn){                       
    if(conn!=null){                                    
      try {                                        
        conn.close();                                   
      } catch (Exception e) {                               
        e.printStackTrace();                               
      }                                          
    }                                           
  } 

}

生成與數(shù)據(jù)庫相對應(yīng)的java實(shí)體類:

package entity;

public class Test {
  private String a;
  private String b;
  private String c;  
  private String d;
  private String e;
  private String f;
  private String g;
  private String h;
  private String i;
  private String j;
  public String getA() {
    return a;
  }
  public void setA(String a) {
    this.a = a;
  }
  public String getB() {
    return b;
  }
  public void setB(String b) {
    this.b = b;
  }
  public String getC() {
    return c;
  }
  public void setC(String c) {
    this.c = c;
  }
  public String getD() {
    return d;
  }
  public void setD(String d) {
    this.d = d;
  }
  public String getE() {
    return e;
  }
  public void setE(String e) {
    this.e = e;
  }
  public String getF() {
    return f;
  }
  public void setF(String f) {
    this.f = f;
  }
  public String getG() {
    return g;
  }
  public void setG(String g) {
    this.g = g;
  }
  public String getH() {
    return h;
  }
  public void setH(String h) {
    this.h = h;
  }
  public String getI() {
    return i;
  }
  public void setI(String i) {
    this.i = i;
  }
  public String getJ() {
    return j;
  }
  public void setJ(String j) {
    this.j = j;
  }
  

}

將excel表格數(shù)據(jù)插入數(shù)據(jù)庫,先讀取excel表格數(shù)據(jù)

package readExcel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.xssf.usermodel.XSSFWorkbook;


public class ReadExcel {

  /**
   * @param args
   * @throws IOException 
   */
  
  public List<List<String>> readExcel(File file) throws IOException{
    List<List<String>> list=new ArrayList<List<String>>();
    if(!file.exists()){
      System.out.println("文件不存在");
    }else{
      InputStream fis=new FileInputStream(file);  
      list=parseExcel(file,fis);
    }
    return list;    
  }
  
  public List<List<String>> parseExcel(File file,InputStream fis) throws IOException{
    Workbook workbook=null;
    List<List<String>> list=new ArrayList<List<String>>();
    if(file.toString().endsWith("xls")){
      workbook=new HSSFWorkbook(fis);
    }else if(file.toString().endsWith("xlsx")){
      workbook=new XSSFWorkbook(fis);
    }else{
      System.out.println("文件不是excel文檔類型 ,此處無法讀取");
    }
    for(int i=0;i<workbook.getNumberOfSheets();i++){
      Sheet sheet=workbook.getSheetAt(i); 
      if(sheet!=null){        
        int lastRow=sheet.getLastRowNum();
        //獲取表格中的每一行
        for(int j=0;j<=lastRow;j++){
          Row row=sheet.getRow(j);
          short firstCellNum=row.getFirstCellNum();
          short lastCellNum=row.getLastCellNum();  
          List<String> rowsList=new ArrayList<String>();
          if(firstCellNum!=lastCellNum){            
            //獲取每一行中的每一列
            for(int k=firstCellNum;k<lastCellNum;k++){
              Cell cell=row.getCell(k);
              if(cell==null){
                rowsList.add("");
              }else{
                rowsList.add(chanegType(cell));
              }
            }
          }else{
            System.out.println("該表格只有一列");
          }
          list.add(rowsList);
        }
        
      }
    }
    return list;  
  }
  
  public String chanegType(Cell cell){
    String result = new String(); 
    switch (cell.getCellType()) { //獲取單元格的類型
    case HSSFCell.CELL_TYPE_NUMERIC:// 數(shù)字類型 
      if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){ //如果是數(shù)值類型
        short format = cell.getCellStyle().getDataFormat(); //獲取這個單元的類型對應(yīng)的數(shù)值
        SimpleDateFormat sdf = null; 
        if(format == 14 || format == 31 || format == 57 || format == 58){ //如果數(shù)值為14,31,57,58其中的一種 
          //對應(yīng)的日期格式為 2016-03-01這種形式,
          sdf = new SimpleDateFormat("yyyy-MM-dd"); 
          double value = cell.getNumericCellValue(); 
          Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); 
          result = sdf.format(date);//得到y(tǒng)yyy-MM-dd這種格式日期
        }else if (format == 20 || format == 32) { 
          //時間 
          sdf = new SimpleDateFormat("HH:mm"); 
          double value = cell.getNumericCellValue(); 
          Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value); 
          result = sdf.format(date);//得到HH:mm
        } else {
          double value = cell.getNumericCellValue(); 
          CellStyle style = cell.getCellStyle(); 
          DecimalFormat dataformat = new DecimalFormat(); 
          String temp = style.getDataFormatString(); 
          // 單元格設(shè)置成常規(guī) 
          if (temp.equals("General")) { 
            dataformat.applyPattern("#"); 
          } 
          result = dataformat.format(value); //得到單元格數(shù)值
        }
      } 
      break; 
    case HSSFCell.CELL_TYPE_STRING:// String類型 
      result = cell.getRichStringCellValue().toString(); 
      break; 
    case HSSFCell.CELL_TYPE_BLANK: 
      result = ""; 
    default: 
      result = ""; 
      break; 
    } 
    return result;    
  }  
}

將讀取到的excel表格數(shù)據(jù)插入到數(shù)據(jù)庫中去

package importdata;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

import entity.Test;
import readExcel.ReadExcel;
import jdbc.BaseDAO;
public class inportData {
  
  
  
  public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    List<List<String>> list = new ArrayList<List<String>>();
    ReadExcel readExcel=new ReadExcel();
    File file=new File("d:/test.xlsx");
    list=readExcel.readExcel(file);
    
    Test test=new Test();
    Connection conn=BaseDAO.getConnection();
    PreparedStatement ps=null;
    int i=1;
    for(List<String> rowlist:list){
      if(rowlist!=null){
        test.setA(rowlist.get(0).toString());
        test.setB(rowlist.get(1).toString());
        test.setC(rowlist.get(2).toString());
        test.setD(rowlist.get(3).toString());      
        test.setE(rowlist.get(4).toString());
        test.setF(rowlist.get(5).toString());
        test.setG(rowlist.get(6).toString());
        test.setH(rowlist.get(7).toString());
        test.setI(rowlist.get(8).toString());
        test.setJ(rowlist.get(9).toString());
        String sql="insert into TEST(A,B,C,D,E,F,G,H,I,J) values(?,?,?,?,?,?,?,?,?,?)";
        ps=conn.prepareStatement(sql);
        ps.setString(1,test.getA());
        ps.setString(2,test.getB());
        ps.setString(3,test.getC());
        ps.setString(4,test.getD());
        ps.setString(5,test.getE());
        ps.setString(6,test.getF());
        ps.setString(7,test.getG());
        ps.setString(8,test.getH());
        ps.setString(9,test.getI());
        ps.setString(10,test.getJ());
        int n=ps.executeUpdate();
        if(n!=1){
          System.out.println("數(shù)據(jù)插入數(shù)據(jù)庫失敗");
        }
        System.out.println("第"+i+"條數(shù)據(jù)插入成功");
        System.out.println();
        i++;
      }
    }
    
    
  }

}

將數(shù)據(jù)庫中的數(shù)據(jù)查詢出來并以excel表格的形式生成報表

package export;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;

import entity.Test;

import jdbc.BaseDAO;

public class Export {
  
  
  public static void createExcel(List<Test> list){
    FileOutputStream fos=null;
    Workbook workbook=new XSSFWorkbook();  
    Sheet sheet=workbook.createSheet("測試文件");
    String[] title={"第一列","第二列","第三列","第四列","第五列","第六列","第七列","第八列","第九列","第十列"};
    Row row=sheet.createRow((short)0);
    int i=0;
    for(String s:title){
      Cell cell=row.createCell(i);
      cell.setCellValue(s);
      i++;
    }
    int j=1;
    for(Test t:list){
      //創(chuàng)建第二行
      Row rowData=sheet.createRow((short)j);
      //第一列數(shù)據(jù)
      Cell cell0=rowData.createCell((short)0);
      cell0.setCellValue(t.getA());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第二列數(shù)據(jù)
      Cell cell1=rowData.createCell((short)1);
      cell1.setCellValue(t.getB());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第三列數(shù)據(jù)
      Cell cell2=rowData.createCell((short)2);
      cell2.setCellValue(t.getC());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第四列數(shù)據(jù)
      Cell cell3=rowData.createCell((short)3);
      cell3.setCellValue(t.getD());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第五列數(shù)據(jù)
      Cell cell4=rowData.createCell((short)4);
      cell4.setCellValue(t.getE());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第六列數(shù)據(jù)
      Cell cell5=rowData.createCell((short)5);
      cell5.setCellValue(t.getF());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第七列數(shù)據(jù)
      Cell cell6=rowData.createCell((short)6);
      cell6.setCellValue(t.getG());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第八列數(shù)據(jù)
      Cell cell7=rowData.createCell((short)7);
      cell7.setCellValue(t.getH());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第九列數(shù)據(jù)
      Cell cell8=rowData.createCell((short)8);
      cell8.setCellValue(t.getI());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      //第十列數(shù)據(jù)
      Cell cell9=rowData.createCell((short)9);
      cell9.setCellValue(t.getJ());
      //設(shè)置單元格的寬度
      sheet.setColumnWidth((short)0, (short)10000);
      j++;
    }
    try {
      //導(dǎo)出數(shù)據(jù)庫文件保存路徑
      fos=new FileOutputStream("D:/export.xlsx");
      /*if(fos.toString().endsWith("xlsx")){
        workbook=new XSSFWorkbook();
      }else if(fos.toString().endsWith("xls")){
        workbook=new HSSFWorkbook();
      }*/
      //將工作簿寫入文件
      workbook.write(fos);  
      System.out.println("導(dǎo)出文件成功");
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      System.out.println("導(dǎo)出文件失敗");
    }
  }
  public static void main(String[] args) throws Exception {
    //連接數(shù)據(jù)庫
    Connection conn=BaseDAO.getConnection();
    PreparedStatement ps=null;    
    String sql="select * from TEST";
    //執(zhí)行sql語句
    ps=conn.prepareStatement(sql);
    //查詢數(shù)據(jù)庫之后得到的結(jié)果
    ResultSet rs=ps.executeQuery();
    List<Test> list=new ArrayList<Test>();
    //遍歷查詢結(jié)果
    while(rs.next()){
      Test test=new Test();
      test.setA(rs.getString("A"));
      test.setB(rs.getString("B"));
      test.setC(rs.getString("C"));
      test.setD(rs.getString("D"));
      test.setE(rs.getString("E"));
      test.setF(rs.getString("F"));
      test.setG(rs.getString("G"));
      test.setH(rs.getString("H"));
      test.setI(rs.getString("I"));
      test.setJ(rs.getString("J"));
      list.add(test);      
    }
    createExcel(list);
  }
  
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • springboot jpaRepository為何一定要對Entity序列化

    springboot jpaRepository為何一定要對Entity序列化

    這篇文章主要介紹了springboot jpaRepository為何一定要對Entity序列化,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • IDEA2020.3創(chuàng)建web工程的完整步驟

    IDEA2020.3創(chuàng)建web工程的完整步驟

    這篇文章主要給大家介紹了關(guān)于IDEA2020.3創(chuàng)建web工程的完整步驟,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • CentOS 7下JDK8的詳細(xì)安裝步驟

    CentOS 7下JDK8的詳細(xì)安裝步驟

    這篇文章主要為大家介紹了CentOS 7下JDK8的詳細(xì)安裝步驟,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-11-11
  • Java內(nèi)存模型之happens-before概念詳解

    Java內(nèi)存模型之happens-before概念詳解

    happens-before原則非常重要,它是判斷數(shù)據(jù)是否存在競爭、線程是否安全的主要依據(jù),依靠這個原則,我們解決在并發(fā)環(huán)境下兩操作之間是否可能存在沖突的所有問題。下面我們就一個簡單的例子稍微了解下happens-before知識,感興趣的朋友一起看看吧
    2021-06-06
  • Java try catch finally異常處理組合詳解

    Java try catch finally異常處理組合詳解

    這篇文章主要介紹了Java try catch finally異常處理組合詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-05-05
  • 在idea中添加JDK的簡單圖文教程

    在idea中添加JDK的簡單圖文教程

    這篇文章主要介紹了如何在IntelliJ IDEA中配置JDK,講解了打開軟件、進(jìn)入Project Structure、選擇SDKs、添加或選擇JDK版本,最后確認(rèn)并重啟IDEA,需要的朋友可以參考下
    2024-12-12
  • 詳解jvm中的標(biāo)量替換

    詳解jvm中的標(biāo)量替換

    這篇文章主要介紹了詳解jvm中的標(biāo)量替換,幫助大家更好的理解和使用Java虛擬機(jī),感興趣的朋友可以了解下
    2020-09-09
  • Springboot任務(wù)之異步任務(wù)的使用詳解

    Springboot任務(wù)之異步任務(wù)的使用詳解

    今天學(xué)習(xí)了一個新技能SpringBoot實(shí)現(xiàn)異步任務(wù),所以特地整理了本篇文章,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • java代碼mqtt接收發(fā)送消息方式

    java代碼mqtt接收發(fā)送消息方式

    這篇文章主要介紹了java代碼mqtt接收發(fā)送消息方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • SpringBoot中的server.context-path的實(shí)現(xiàn)

    SpringBoot中的server.context-path的實(shí)現(xiàn)

    本文主要介紹了SpringBoot中的server.context-path的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2024-08-08

最新評論

微山县| 台东县| 东乡县| 彰化市| 鄯善县| 临猗县| 吐鲁番市| 辽宁省| 德钦县| 祁东县| 常州市| 洱源县| 吉林市| 淅川县| 金平| 青海省| 五峰| 克山县| 青岛市| 定日县| 景洪市| 大关县| 建水县| 共和县| 金沙县| 普兰县| 大理市| 湘阴县| 陆河县| 绥阳县| 中山市| 成武县| 容城县| 山阳县| 安义县| 北宁市| 庄浪县| 鸡西市| 丹棱县| 沂源县| 西畴县|