java write excel file

Original address https://blog.csdn.net/qq_33685734/article/details/77737387

Original address https://www.cnblogs.com/chenyq/p/5530970.html

Java writes to excel file poi, supports xlsx and xls, no file is automatically created

Copy code
package com.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.exception.SimpleException;

  
/** 
 * Reading data from excel/writing to excel has a header, and the content of each column in the header corresponds to the attribute of the entity class 
 *  
 * @author nagsh 
 *  
 * /   
public  class ExcelManage {  


    public static void main(String[] args) throws IOException {  
        String path = "E:/";  
        String fileName = "List of Insured Persons (New) 04" ;  
        String fileType = "xlsx";  
        List<InsuraceExcelBean> list = new ArrayList<>();
        for(int i=0; i<6; i++){
            InsuraceExcelBean bean = new InsuraceExcelBean();  
            bean.setInsuraceUser("test"+i);
            bean.setBankCardId("4444444444"+i+","+"55544444444444"+i+","+"999999999999999"+i);
            bean.setIdCard("666666"+i);
            bean.setBuyTime("2016-05-06");
            bean.setInsEndTime("2016-05-07");
            bean.setInsStartTime("2017-05-06");
            bean.setMoney("20,000");
            bean.setType( "Deposit Card" );
            
            list.add(bean);
        }
        String title[] = {"Name of the insured","ID number","Account type","Bank card number","Insured amount (RMB)","Purchase time","Insurance policy effective time","Insurance policy Expiration time" };  
 //         createExcel("E:/List of insured persons (new).xlsx","sheet1",fileType,title);  
        
        writer(path, fileName, fileType,list,title);  
    }  
    
    @SuppressWarnings("resource")
    public static void writer(String path, String fileName,String fileType,List<InsuraceExcelBean> list,String titleRow[]) throws IOException {  
        Workbook wb = null; 
        String excelPath = path+File.separator+fileName+"."+fileType;
        File file = new File(excelPath);
        Sheet sheet = null ;
         // Create a working document object    
        if (! file.exists()) {
             if (fileType.equals("xls" )) {
                wb = new HSSFWorkbook();
                
            } else if(fileType.equals("xlsx")) {
                
                    wb = new XSSFWorkbook();
            } else {
                 throw  new SimpleException("The file format is incorrect" );
            }
            // Create sheet object    
            sheet = (Sheet) wb.createSheet("sheet1" );  
            OutputStream outputStream = new FileOutputStream(excelPath);
            wb.write(outputStream);
            outputStream.flush();
            outputStream.close();
            
        } else {
            if (fileType.equals("xls")) {  
                wb = new HSSFWorkbook();  
                
            } else if(fileType.equals("xlsx")) { 
                wb = new XSSFWorkbook();  
                
            } else {  
                 throw  new SimpleException("The file format is incorrect" );
            }  
        }
         // Create a sheet object    
        if (sheet== null ) {
            sheet = (Sheet) wb.createSheet("sheet1");  
        }
        
        // Add header   
        Row row = sheet.createRow(0 );
        Cell cell = row.createCell(0);
        row.setHeight((short) 540); 
        cell.setCellValue( "List of Insured Persons");     // Create the first row     
        
        CellStyle style = wb.createCellStyle(); // Style object      
         // Set the background color of the cell to light blue   
        style.setFillForegroundColor(HSSFColor.PALE_BLUE .index);
        
        style.setVerticalAlignment(CellStyle.VERTICAL_CENTER); // Vertical       
        style.setAlignment(CellStyle.ALIGN_CENTER); // Horizontal    
        style.setWrapText( true ); // Specify automatic line 
       
        wrapping when the cell content is not displayed cell.setCellStyle(style); // Style, centered 
        
        Font font = wb.createFont();  
        font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
        font.setFontName( "Song Ti" );  
        font.setFontHeight((short) 280);  
        style.setFont(font);  
        // Cell merge      
         //The four parameters are: start row, start column, end row, end column       
        sheet.addMergedRegion( new CellRangeAddress(0, 0, 0, 7 ));  
        sheet.autoSizeColumn ( 5200 );
        
        row = sheet.createRow(1);     // Create the second row     
        for ( int i = 0;i <titleRow.length;i++ ){  
            cell = row.createCell(i);  
            cell.setCellValue(titleRow[i]);  
            cell.setCellStyle(style); // Style, centered 
            sheet.setColumnWidth(i, 20 * 256 );
        }  
        row.setHeight((short) 540); 

        // Circularly write row data    
        for ( int i = 0; i <list.size(); i++ ) {  
            row = (Row) sheet.createRow(i+2);  
            row.setHeight((short) 500); 
            row.createCell(0).setCellValue(( list.get(i)).getInsuraceUser());
            row.createCell(1).setCellValue(( list.get(i)).getIdCard());
            row.createCell(2).setCellValue(( list.get(i)).getType());
            row.createCell(3).setCellValue(( list.get(i)).getBankCardId());
            row.createCell(4).setCellValue(( list.get(i)).getMoney());
            row.createCell(5).setCellValue(( list.get(i)).getBuyTime());
            row.createCell(6).setCellValue(( list.get(i)).getInsStartTime());
            row.createCell(7).setCellValue(( list.get(i)).getInsEndTime());
        }  
        
        // Create a file stream    
        OutputStream stream = new FileOutputStream(excelPath);  
         // Write data    
        wb.write(stream);  
         // Close the file stream    
        stream.close();  
    }  
    
}  
Copy code

============================================================================================================================================================================================================================================================================================================================================================================================================

//定义表头
String[] title={"序号","姓名","年龄"};
//创建excel工作簿
HSSFWorkbook workbook=new HSSFWorkbook();
//创建工作表sheet
HSSFSheet sheet=workbook.createSheet();
//创建第一行
HSSFRow row=sheet.createRow(0);
HSSFCell cell=null;
//插入第一行数据的表头
for(int i=0;i<title.length;i++){
    cell=row.createCell(i);
    cell.setCellValue(title[i]);
}
//写入数据
for (int i=1;i<=10;i++){
    HSSFRow nrow=sheet.createRow(i);
    HSSFCell ncell=nrow.createCell(0);
    ncell.setCellValue(""+i);
    ncell=nrow.createCell(1);
    ncell.setCellValue("user"+i);
    ncell=nrow.createCell(2);
    ncell.setCellValue("24");
}
//创建excel文件
File file=new File("f://poi.xlsx");
try {
    file.createNewFile();
    //将excel写入
    FileOutputStream stream= FileUtils.openOutputStream(file);
    workbook.write(stream);
    stream.close();
} catch (IOException e) {
    e.printStackTrace();
}



在maven仓库中导入jar包

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.3</version>
</dependency>



Guess you like

Origin blog.csdn.net/Jay112011/article/details/80102197