jxl

Java to generate and manipulate Excel files


package demo.dcn.vo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
public class Excel {
	/**
	 * @param args
	 * Excel read and write program
	 * @throws IOException
	 * @throws BiffException
	 */
	public static void main(String[] args) throws BiffException, IOException {
		writeExcel();
		readExcel();
	}
	public static void readExcel() throws BiffException, IOException{
		List list = new ArrayList();
		Workbook rwb =null;
		Cell cell = null;
		InputStream stream = new FileInputStream("E:\\xml\\x.xls");//Create an output stream
		rwb = Workbook.getWorkbook(stream); //Get the Excel file object
		Sheet sheet = rwb.getSheet(0);//Get the default first sheet of the specified sheet of the file
		for(int i=0;i<sheet.getRows();i++){//Number of rows (the directory of the table header is not required, starting from 1
			String[] str = new String[sheet.getColumns()]; //Create an array to store the value of each column
			for(int k=0;k<sheet.getColumns();k++){
				//Get the value of row i, column k
				cell = sheet.getCell(k,i);
				str[k] = cell.getContents();
				/ / Store the column just obtained into the list
			     list.add(str);
			}
		}
		for(int i=0;i<list.size();i++){
			  String[] str = (String[])list.get(i);
			  for(int j=0;j<str.length;j++){
				  System.out.println(str[j]);
			  }
		  }
	}
	
	/**
	 * Write excel file
	 */
	public static void writeExcel(){
		 String[] title = {"Number","Product Name","Product Price","Product Quantity","Production Date","Origin","Export or not"};
		 try{
			 
	            long start = System.currentTimeMillis(); // get start time  
	            String filePath = "d:\\testJXL.xls"; // The path of the output excel   
	            WritableWorkbook wwb; // Create an Excel workbook   
	            OutputStream os = new FileOutputStream(filePath);  
	            wwb=Workbook.createWorkbook(os); // Create a new jxl file, that is, generate testJXL.xls under the d drive    
	            WritableSheet sheet = wwb.createSheet("Product List", 0); // Add the first sheet and set the name of the first Sheet
	            Label label;
	            
	            for(int i=0;i<title.length;i++){   
	                // Label(x,y,z) represents the x+1 column of the cell, the y+1 row, the content z   
	                // Indicate the location and content of the cell in the child object of the Label object   
	                label = new Label(i,0,title[i]);
	                label = new Label(i, 0, title[i], getHeader());
	                // Add the defined cells to the worksheet   
	                sheet.addCell(label);   
	            }
	            //below is the fill data   
	             /*   
	              * To save numbers to cells, you need to use jxl.write.Number
	              * must use its full path, otherwise an error will occur
	             * */
	           // populate the product number   
	            jxl.write.Number number = new jxl.write.Number(0,1,20071001);   
	            sheet.addCell(number);
	            // fill in the product name   
	             label = new Label(1,1,"Golden Pigeon Seeds");   
	            sheet.addCell(label);
	            /*
		            * Define a common format for displaying amounts
		              * jxl will automatically implement rounding
		             * For example 2.456 will be formatted as 2.46, 2.454 will be formatted as 2.45
		             * */
		            jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#,###.00");   
		            jxl.write.WritableCellFormat wcf = new jxl.write.WritableCellFormat (nf);
		            // populate the product price   
		            jxl.write.Number nb = new jxl.write.Number(2,1,200000.45,wcf);   
		            sheet.addCell(nb);   
		            // populate the product quantity   
		             jxl.write.Number numb = new jxl.write.Number(3,1,200);   
		            sheet.addCell(numb);
		            /*
		              * Define the public format for displaying dates
		            * Such as: yyyy-MM-dd hh:mm
		             * */
		           SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");   
		            String newdate = sdf.format(new java.util.Date());   
		            // fill in the production date   
		            label = new Label(4,1,newdate);   
		            sheet.addCell(label);   
		            // populate the origin   
		             label = new Label(5,1,"Shaanxi Xi'an");   
		            sheet.addCell(label);   
		            /*
		             * show boolean value
		             * */
		            jxl.write.Boolean bool = new jxl.write.Boolean (6.1, true);   
		            sheet.addCell(bool);   
		             /*
		             * Merge Cells
		             * Implemented by writablesheet.mergeCells(int x, int y, int m, int n);
		              * means merge from column x+1, row y+1 to column m+1, row n+1
		             *   
		             * */
		            sheet.mergeCells(0,3,2,3);   
		            label = new Label(0,3,"Merged three cells");   
		            sheet.addCell(label);
		            /*
		              *   
		              * Define public font format
		              * Use as a template by getting the style of a font
		             * First get the first sheet through web.getSheet(0)
		             * Then get the second column of the first sheet, the first row is the font of "product name"   
		            * */
		            CellFormat cf = wwb.getSheet (0) .getCell (1, 0) .getCellFormat ();   
		            WritableCellFormat wc = new WritableCellFormat();   
		            // set center   
		             wc.setAlignment (Alignment.CENTRE);   
		             // set border line   
		           wc.setBorder(Border.ALL, BorderLineStyle.THIN);   
		            // set the background color of the cell   
		           wc.setBackground(jxl.format.Colour.RED);   
		            label = new Label(1,5,"字体",wc);   
		           sheet.addCell(label);   
		 
		            // set font   
		           jxl.write.WritableFont wfont = new jxl.write.WritableFont(WritableFont.createFont("隶书"),20);   
		            WritableCellFormat font = new WritableCellFormat(wfont);   
		            label = new Label(2,6,"Lishu",font);   
		             sheet.addCell(label);   
		               
		          // data input   
		           wwb.write();   
		            // close the file   
		            wwb.close();   
		           long end = System.currentTimeMillis();   
		            System.out.println("----The time taken to complete this operation is: "+(end-start)/1000);
		 }catch(Exception e){
			 System.out.println("---An exception occurred---");   
             e.printStackTrace ();
		 }
	}
	
	
	/**
	  * Set the style of the header
	  * @return
	  */
	 public static WritableCellFormat getHeader(){
	  WritableFont font = new WritableFont(WritableFont.TIMES, 10 ,WritableFont.BOLD);//Define the font
	  try {
	   font.setColour(Colour.BLUE);//Blue font
	  } catch (WriteException e1) {
	   // TODO automatically generates catch block
	   e1.printStackTrace();
	  }
	  WritableCellFormat format = new  WritableCellFormat(font);
	  try {
	   format.setAlignment (jxl.format.Alignment.CENTRE); // 左右 居中
	   format.setVerticalAlignment (jxl.format.VerticalAlignment.CENTRE); // 上下 居中
	   format.setBorder(Border.ALL,BorderLineStyle.THIN,Colour.BLACK);//Black border
	   format.setBackground(Colour.YELLOW);//Yellow background
	  } catch (WriteException e) {
	   // TODO automatically generates catch block
	   e.printStackTrace ();
	  }
	  return format;
	 }
	
	
	
}
 public static boolean writeExcel(OutputStream os, List<String> columns, List<Map<String, Object>> objData) {
        // Create an Excel workbook that can be written (by default, the generated file is under tomcat/bin)
        WritableWorkbook wwb=null;
        try {
            wwb=Workbook.createWorkbook(os);
            WritableSheet sheet=wwb.createSheet("First Sheet", 0);
            // start writing the first line (ie the title bar)
            for(int i=0; i < columns.size(); i++) {
                // used to write text content to the worksheet
                Label label=null;
                // Specify the cell position in the construction of the Label object (parameters represent the number of columns, rows, and content in turn)
                label=new Label(i, 0, columns.get(i));
                // Add the defined cells to the worksheet
                sheet.addCell(label);
            }
            // Loop through the data in the table
            if(objData.isEmpty()) {
                return false;
            } else {
                for(int i=0; i < objData.size(); i++) {
                    // Convert to map collection {activyName: test function, count: 2}
                    Map<String, Object> map=(Map<String, Object>)objData.get(i);
                    // Loop through the subset in the output map: both column values
                    for(int j=0;j<columns.size();j++){
                        for(Map.Entry<String, Object> entry : map.entrySet()) {
                            // ps: Because the ""general"" export function is required, the loop here is not get("Name"), but through map.get(o)
                            if(entry.getKey()==columns.get(j)){
                                sheet.addCell(new Label(j, i + 1, String.valueOf(entry.getValue())));
                            }
                        }
                    }
                    
                }
            }
            // data input
            wwb.write();
            // close the file
            wwb.close();
            // close the output stream
            os.close();
        } catch(Exception e) {
            e.printStackTrace ();
            return false;
        }
        return true;
    }

/**
     * Download the file to the client, and the download box will pop up.
     * @param response(HttpServletResponse)
     * @param file (the file to be downloaded)
     * @param isDel (whether to delete the file after the download is complete)
     * @throws IOException
     */
    public static void exportFile(HttpServletResponse response, File file, boolean isDel)  {
        OutputStream out=null;
        InputStream in=null;
        try {
            // get the filename
            String filename=URLEncoder.encode(file.getName(), "UTF-8");
            // define the output type (download)
            response.setContentType("application/force-download");
            response.setHeader("Location", filename);
            // define the output file header
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            out=response.getOutputStream();
            in=new FileInputStream(file.getPath());

            byte[] buffer=new byte[1024];
            int i=-1;
            while((i=in.read(buffer)) != -1) {
                out.write(buffer, 0, i);
            }
            in.close();
            out.close();
        } catch(Exception e) {
            e.printStackTrace ();
        }
        if(isDel) {
            // Delete the file, close all Streams before deleting.
            file.delete();
        }
    }

    /**
     * Create filename and temp file
     * @throws IOException
     */
    public static File createFile(String name) {
        // create the current day
        Date date=new Date();
        // format the date
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        // format date (generate filename)
        String filename=sdf.format(date);
        // Create a file
        File f=new File(name + filename + ".xls");
        try {
            f.createNewFile();
        } catch(IOException e) {
            e.printStackTrace ();
        }
        return f;
    }




Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326693514&siteId=291194637
jxl