天天看點

Jxl 操作 excel 常用方法總結二

package common.excelTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import jxl.Cell;
import jxl.CellType;
import jxl.DateCell;
import jxl.Range;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.CellFormat;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Formula;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCell;
import jxl.write.WritableCellFeatures;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;


public class WriteExcelTest {
static HashMap map = new HashMap();

public static void main(String[] args) {
   try {
//    copyDateFormat(new File("c:\\a.xls"), 0, "c:\\copy of a.xls");
//    writeExcelUseFormat("c:\\format.xls","test");

//    buildNewFormTemplete(new File("c:/templete.xls"),new File( "c:/buildNewFormTemplete.xls"));
//    modifyDirectly1(new File("c:/templete.xls"));
//    modifyDirectly2(new File("c:/templete.xls"));
    copyDateAndFormat(new File("c:/a.xls"), 0, "c:/a2.xls");
   } catch (Exception e) {
    // TODO 自動生成 catch 塊
    e.printStackTrace();
   }
}



public static void modifyDirectly2(File inputFile) throws Exception{
   Workbook w1 = Workbook.getWorkbook(inputFile);
   WritableWorkbook w2 = Workbook.createWorkbook(inputFile, w1);
   WritableSheet sheet = w2.getSheet(0);

   WritableCell cell = null;
   CellFormat cf = null;

   //加粗
   cell = sheet.getWritableCell(0,0);
   WritableFont bold = new WritableFont(WritableFont.ARIAL,
     WritableFont.DEFAULT_POINT_SIZE,
     WritableFont.BOLD);
   cf = new WritableCellFormat(bold);
   cell.setCellFormat(cf);

   //設定下劃線
   cell = sheet.getWritableCell(0,1);
   WritableFont underline = new WritableFont(WritableFont.ARIAL,
     WritableFont.DEFAULT_POINT_SIZE,
     WritableFont.NO_BOLD,
     false,
     UnderlineStyle.SINGLE);
   cf = new WritableCellFormat(underline);
   cell.setCellFormat(cf);

   //直截添加可以覆寫掉
   setCellValueDirectly(sheet,sheet.getCell(0, 2),new Double(4),CellType.NUMBER);

   w2.write();
   w2.close();
}






public static void modifyDirectly1(File file) {
   try{
    // Excel獲得檔案
    Workbook wb = Workbook.getWorkbook(file);
    // 打開一個檔案的副本,并且指定資料寫回到原檔案
    WritableWorkbook book = Workbook.createWorkbook(file,
      wb);
    WritableSheet sheet0 = book.getSheet(0);
    sheet0.addCell(new Label(0, 1, "陳小穩"));

    // 添加一個工作表
    WritableSheet sheet = book.createSheet( " 第二頁 " , 1 );
    sheet.addCell( new Label( 0 , 0 , " 第二頁的測試資料 " ));
    book.write();
    book.close();
   } catch (Exception e) {
    System.out.println(e);
   }
}



public static void buildNewFormTemplete(File inputFile, File outputFile){
   try{
    // Excel獲得檔案
    Workbook wb = Workbook.getWorkbook(inputFile);
    // 打開一個檔案的副本,并且指定資料寫回到原檔案
    WritableWorkbook book = Workbook.createWorkbook(outputFile,
      wb);
    WritableSheet sheet0 = book.getSheet(0);
    sheet0.addCell(new Label(0, 1, "陳小穩"));

    // 添加一個工作表
    WritableSheet sheet = book.createSheet( " 第二頁 " , 1 );
    sheet.addCell( new Label( 0 , 0 , " 第二頁的測試資料 " ));

    book.write();
    book.close();
   } catch (Exception e) {
    System.out.println(e);
   }
}




public static void copyDateAndFormat(File inputFile, int inputFileSheetIndex, String outputFilePath) throws Exception {
   Workbook book = null;
   Cell cell = null;
   //1.避免亂碼的設定
   WorkbookSettings setting = new WorkbookSettings();
   java.util.Locale locale = new java.util.Locale("zh","CN");
   setting.setLocale(locale);
   setting.setEncoding("ISO-8859-1");
   book = Workbook.getWorkbook(inputFile, setting);
   Sheet readonlySheet = book.getSheet(inputFileSheetIndex);

   OutputStream os=new FileOutputStream(outputFilePath);//輸出的Excel檔案URL
   WritableWorkbook wwb = Workbook.createWorkbook(os);//建立可寫工作薄
   WritableSheet writableSheet = wwb.createSheet(readonlySheet.getName(), 0);//建立可寫工作表

   //2.謄寫不同資料格式的資料
   for (int rowIndex = 0; rowIndex < readonlySheet.getRows(); rowIndex++) {
    for (int colIndex = 0; colIndex < readonlySheet.getColumns(); colIndex++) {
     cell = readonlySheet.getCell(colIndex, rowIndex);
     //A2B2為合并的單元格,A2有内容,B2為空
//     if(colIndex == 0 && rowIndex == 1){
//      System.out.println(colIndex + "," + rowIndex + " type:" + cell.getType() +" :" + cell.getContents());
//     }

     //【有各種設定格式】
     if(cell.getType() == CellType.DATE || cell.getType() == CellType.DATE_FORMULA){
      writableSheet.addCell(
        new jxl.write.DateTime(
          colIndex
          , rowIndex
          , ((DateCell)cell).getDate(),
          new jxl.write.WritableCellFormat(
            cell.getCellFormat()
          )
        )
      );
     }else if(cell.getType() == CellType.NUMBER || cell.getType() == CellType.NUMBER_FORMULA){
      writableSheet.addCell(
        new jxl.write.Number(
          colIndex
          , rowIndex
          , ((jxl.NumberCell)cell).getValue(),
          new jxl.write.WritableCellFormat(
            cell.getCellFormat()
          )
        )
      );
     }else if(cell.getType() == CellType.EMPTY){
      //空的以及合并單元格中第一列外的
//      System.out.println("EMPTY:"+cell.getContents());
//      System.err.println("空單元格 at " + colIndex + "," + rowIndex +" content:" + cell.getContents());
     }else if(cell.getType() == CellType.LABEL || cell.getType() == CellType.STRING_FORMULA){
      writableSheet.addCell(
        new Label(
          colIndex
          , rowIndex
          , cell.getContents()
          , new jxl.write.WritableCellFormat(
            cell.getCellFormat()
          )
        )
      );
     }else{
      System.err.println("其它單元格類型:" + cell.getType() + " at " + colIndex + "," + rowIndex +" content:" + cell.getContents());
     }

//     if(cell.getType() == CellType.STRING_FORMULA){
//     System.err.println(colIndex + "," + rowIndex +":" + cell.getContents() +" type:" + cell.getType());
//     }
    }
   }


   //3.處理合并單元格的事情(複制合并單元格格式)
   Range[] range = readonlySheet.getMergedCells();
   for (int i = 0; i < range.length; i++) {
//    System.out.println("第"+i+"處合并的單元格:"
//    +",getTopLeft="+range[i].getTopLeft().getColumn()
//    +","+range[i].getTopLeft().getRow()
//    +",getBottomRight="+range[i].getBottomRight().getColumn()
//    +","+range[i].getBottomRight().getRow()
//    );
    //topleftXIndex, topleftYIndex, bottomRightXIndex, bottomRightYIndex
    writableSheet.mergeCells(
      range[i].getTopLeft().getColumn(),
      range[i].getTopLeft().getRow(),
      range[i].getBottomRight().getColumn(),
      range[i].getBottomRight().getRow()
    );
   }

   //4.設定行列高寬
   for (int colIndex = 0; colIndex < readonlySheet.getColumns(); colIndex++) {
    writableSheet.setColumnView(colIndex,readonlySheet.getColumnView(colIndex));
   }
   for (int rowIndex = 0; rowIndex < readonlySheet.getRows(); rowIndex++) {
    writableSheet.setRowView(rowIndex,readonlySheet.getRowView(rowIndex));
   }

   wwb.write();
   wwb.close();
   os.close();
}



public static void writeExcelUseFormat(String outputFilePath,String outputFileSheetName) throws Exception{
   OutputStream os=new FileOutputStream(outputFilePath);//輸出的Excel檔案URL
   WritableWorkbook wwb = Workbook.createWorkbook(os);//建立可寫工作薄
   WritableSheet sheet = wwb.createSheet(outputFileSheetName, 0);//建立可寫工作表


   sheet.addCell(new Label(0, 0, "号碼"));
   sheet.addCell(new Label(1, 0, "有效期"));

   //1.寫入時間的資料格式
   jxl.write.DateFormat df = new jxl.write.DateFormat("yyyy-MM-dd");
   jxl.write.WritableCellFormat wcfDF = new jxl.write.WritableCellFormat(df);
   jxl.write.DateTime labelDTF = new jxl.write.DateTime(1, 1, new Date(), wcfDF); //自定義格式
   sheet.addCell(labelDTF);

   //2.字型樣式
//   WritableFont()方法裡參數說明:
//   這個方法算是一個容器,可以放進去好多屬性
//   第一個: TIMES是字型大小,他寫的是18
//   第二個: BOLD是判斷是否為斜體,選擇true時為斜體
//   第三個: ARIAL
//   第四個: UnderlineStyle.NO_UNDERLINE 下劃線
//   第五個: jxl.format.Colour.RED 字型顔色是紅色的
   jxl.write.WritableFont wf = new jxl.write.WritableFont(WritableFont.TIMES, 18, WritableFont.BOLD, true);
   jxl.write.WritableCellFormat wcfF = new jxl.write.WritableCellFormat(wf);
   wcfF.setWrap(true);//自動換行
   wcfF.setAlignment(jxl.format.Alignment.CENTRE);//把水準對齊方式指定為居中
   wcfF.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//把垂直對齊方式指定為居中
   jxl.write.Label labelC = new jxl.write.Label(0, 1, "This is a Label cell", wcfF);
   sheet.addCell(labelC);

   //3.添加帶有formatting的Number對象
   jxl.write.NumberFormat nf = new jxl.write.NumberFormat("#.##");
   jxl.write.WritableCellFormat wcfN = new jxl.write.WritableCellFormat(nf);
   jxl.write.Number labelNF = new jxl.write.Number(0, 2, 3.1415926, wcfN);
   sheet.addCell(labelNF);

   //4.添加Boolean對象
   jxl.write.Boolean labelB = new jxl.write.Boolean(0, 3, false);
   sheet.addCell(labelB);

   //5.設定一個注解
   WritableCellFeatures cellFeatures = new WritableCellFeatures();
   cellFeatures.setComment("添加Boolean對象");
   labelB.setCellFeatures(cellFeatures);

   //6.單元格内換行
   WritableCellFormat wrappedText = new WritableCellFormat
   (WritableWorkbook.ARIAL_10_PT);
   wrappedText.setWrap(true);//可換行的label樣式
   Label label = new Label(4, 0, "測試,\012測試。。。",wrappedText); // "\012"強制換行
   sheet.addCell(label);

   //7.數字的公式計算
   Number n = new jxl.write.Number(0,9,4.5);//A10
   sheet.addCell(n);
   n = new Number(1,9, 8);//B10
   sheet.addCell(n);
   NumberFormat dp3 = new NumberFormat("#.###"); //設定單元格裡面的數字格式
   WritableCellFormat dp3cell = new WritableCellFormat(dp3);
   dp3cell.setWrap(true);
   Formula f = new Formula(2, 9, "(a10+b10)/2", dp3cell); //設定C10公式
   sheet.addCell(f);
   f = new Formula(3, 9, "SUM(A10:B10)", dp3cell);//設定D10公式
   sheet.addCell(f);

   //8.設定sheet的樣式
   sheet.getSettings().setProtected(true); //設定xls的保護,單元格為隻讀的
   sheet.getSettings().setPassword("123"); //設定xls的密碼
   sheet.getSettings().setDefaultColumnWidth(10); //設定列的預設寬度,2cm左右
   sheet.setRowView(3,200);//設定第4行高度
   sheet.setRowView(2,false);// 這樣可以自動把行高擴充
   sheet.setColumnView(0 , 300);//設定第1列寬度,6cm左右
   sheet.mergeCells(0 , 5, 1, 7);//合并單元格:合并A6B8也就是1列6行 與 2列7行 之間的矩形

   //9.設定邊框
   drawRect(sheet, 5, 6, 7, 6,BorderLineStyle.THICK, Colour.BLACK, null);

   wwb.write();
   wwb.close();
   os.close();
}



public static void drawRect(WritableSheet sheet, int x, int y, int width, int height,BorderLineStyle style,Colour BorderColor, Colour bgColor) throws WriteException {
   for(int w = 0; w < width; w++){
    for(int h = 0; h < height; h ++) {
     WritableCellFormat alignStyle = new WritableCellFormat(); //單元格樣式
     alignStyle.setAlignment(Alignment.CENTRE);   //設定對齊方式
     alignStyle.setVerticalAlignment(VerticalAlignment.CENTRE);//設定對齊方式
     if(h == 0)//畫上
      alignStyle.setBorder(Border.TOP, style, BorderColor);//設定邊框的顔色和樣式

     if(w == 0)//畫左
      alignStyle.setBorder(Border.LEFT, style, BorderColor);//設定邊框的顔色和樣式

     if(w == width - 1)//畫右
      alignStyle.setBorder(Border.RIGHT, style, BorderColor);//設定邊框的顔色和樣式

     if(h == height -1)//畫下
      alignStyle.setBorder(Border.BOTTOM, style, BorderColor);//設定邊框的顔色和樣式
     //drawLine(sheet, x, y, Border.BOTTOM);
     if(bgColor != null)
      alignStyle.setBackground(bgColor); //背靜色
     Label mergelabel = new Label(x, y, "", alignStyle);
     //topleftXIndex, topleftYIndex, bottomRightXIndex, bottomRightYIndex
     //sheet.mergeCells(2, 5, 10, 10);
     sheet.addCell(mergelabel);
     y++;
    }
    y -= height;
    x++;
   }
}



public static ArrayList<String> sampleReadExcel(File inputFile, int inputFileSheetIndex) throws Exception {
   ArrayList<String> list = new ArrayList<String>();
   Workbook book = null;
   Cell cell = null;
   //避免亂碼的設定
   WorkbookSettings setting = new WorkbookSettings();
   java.util.Locale locale = new java.util.Locale("zh","CN");
   setting.setLocale(locale);
   setting.setEncoding("ISO-8859-1");
   book = Workbook.getWorkbook(inputFile, setting);

   Sheet sheet = book.getSheet(inputFileSheetIndex);
   for (int rowIndex = 0; rowIndex < sheet.getRows(); rowIndex++) {// Excel第一行為表頭,是以J初值設為1
    for (int colIndex = 0; colIndex < sheet.getColumns(); colIndex++) {// 隻需從Excel中取出2列
     cell = sheet.getCell(colIndex, rowIndex);
     list.add(cell.getContents());
    }
   }

   //【問題:如果在實際部署的時候沒有寫下面這句是否會導緻不斷消耗掉伺服器的記憶體?jxl裡面有個ReadWrite.java沒有關閉讀的,隻關閉了寫的】
   book.close();

   return list;
}




public static void setCellValueDirectly(WritableSheet sheet, Cell cell, Object newValue, CellType type) throws Exception{
   if(type == CellType.DATE || type == CellType.DATE_FORMULA){
    sheet.addCell(
      new jxl.write.DateTime(
        cell.getColumn()
        , cell.getRow()
        , (Date)newValue,
        new jxl.write.WritableCellFormat(
          cell.getCellFormat()
        )
      )
    );
   }else if(type == CellType.NUMBER || type == CellType.NUMBER_FORMULA){
    sheet.addCell(
      new jxl.write.Number(
        cell.getColumn()
        , cell.getRow()
        , ((Double)newValue).doubleValue(),
        new jxl.write.WritableCellFormat(
          cell.getCellFormat()
        )
      )
    );
   }else if(type == CellType.LABEL || type == CellType.STRING_FORMULA){
    sheet.addCell(
      new Label(
        cell.getColumn()
        , cell.getRow()
        , (String)newValue
        , new jxl.write.WritableCellFormat(
          cell.getCellFormat()
        )
      )
    );
   }else{
    throw new Exception("不支援的其它單元格類型:"+type);
//    System.err.println("不支援的其它單元格類型:" + cell.getType() + " at " + cell.getColumn() + "," + cell.getRow() +" current content:" + cell.getContents());
   }