一.POI簡介html
Jakarta POI 是apache的子項目,目標是處理ole2對象。它提供了一組操縱Windows文檔的Java APIjava
目前比較成熟的是HSSF接口,處理MS Excel(97-2002)對象。它不象咱們僅僅是用csv生成的沒有格式的能夠由Excel轉換的東西,而是真正的Excel對象,你能夠控制一些屬性如sheet,cell等等。apache
二.HSSF概況app
HSSF 是Horrible SpreadSheet Format的縮寫,也即「討厭的電子表格格式」。也許HSSF的名字有點滑稽,就本質而言它是一個很是嚴肅、正規的API。經過HSSF,你能夠用純Java代碼來讀取、寫入、修改Excel文件。ide
HSSF 爲讀取操做提供了兩類API:usermodel和eventusermodel,即「用戶模型」和「事件-用戶模型」。前者很好理解,後者比較抽象,但操做效率要高得多。函數
三.開始編碼工具
1 . 準備工做字體
要求:JDK 1.4+POI開發包ui
能夠到 http://www.apache.org/dyn/closer.cgi/jakarta/poi/ 最新的POI工具包編碼
2 . EXCEL 結構
HSSFWorkbook excell 文檔對象介紹
HSSFSheet excell的表單
HSSFRow excell的行
HSSFCell excell的格子單元
HSSFFont excell字體
HSSFName 名稱
HSSFDataFormat 日期格式
在poi1.7中才有如下2項:
HSSFHeader sheet頭
HSSFFooter sheet尾
和這個樣式
HSSFCellStyle cell樣式
輔助操做包括
HSSFDateUtil 日期
HSSFPrintSetup 打印
HSSFErrorConstants 錯誤信息表
3 .具體用法實例 (採用 usermodel )
如何讀Excel
讀取Excel文件時,首先生成一個POIFSFileSystem對象,由POIFSFileSystem對象構造一個HSSFWorkbook,該HSSFWorkbook對象就表明了Excel文檔。下面代碼讀取上面生成的Excel文件寫入的消息字串:
代碼
POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
String msg = cell.getStringCellValue();
POIFSFileSystem fs=newPOIFSFileSystem(new FileInputStream("d:/test.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
} catch (IOException e) {
e.printStackTrace();
}
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
String msg = cell.getStringCellValue();
如何寫excel,
將excel的第一個表單第一行的第一個單元格的值寫成「a test」。
代碼
POIFSFileSystem fs =new POIFSFileSystem(new FileInputStream("workbook.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short)0);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
4 . 可參考文檔
POI 主頁:http://jakarta.apache.org/poi/,
初學者如何快速上手使用POI HSSF
http://jakarta.apache.org/poi/hssf/quick-guide.html 。
代碼例子 http://blog.java-cn.com/user1/6749/archives/2005/18347.html
裏面有不少例子代碼,能夠很方便上手。
POI的中級應該用
一、遍歷workbook
代碼
// load源文件
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
for (int i = 0; i < wb.getNumberOfSheets(); i++) {
HSSFSheet sheet = wb.getSheetAt(i);
for (int i = sheet.getFirstRowNum(); i < sheet.getLastRowNum(); i ++) {
HSSFRow row = sheet.getRow(i);
if (row != null) {
。。。操做}
}
}
// 目標文件
FileOutputStream fos = new FileOutputStream(objectPath);
//寫文件
swb.write(fos);
fos.close();
二、獲得列和單元格
代碼
HSSFRow row = sheet.getRow(i);
HSSFCell cell = row.getCell((short) j);
三、設置sheet名稱和單元格內容爲中文
代碼
wb.setSheetName(n, "中文",HSSFCell.ENCODING_UTF_16);
cell.setEncoding((short) 1);
cell.setCellValue("中文");
四、單元格內容未公式或數值,能夠這樣讀寫
代碼
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.getNumericCellValue()
五、設置列寬、行高
代碼
sheet.setColumnWidth((short)column,(short)width);
row.setHeight((short)height);
六、添加區域,合併單元格
代碼
Region region = new Region((short)rowFrom,(short)columnFrom,(short)rowTo,(short)columnTo);
sheet.addMergedRegion(region);
//獲得全部區域
sheet.getNumMergedRegions()
七、經常使用方法
根據單元格不一樣屬性返回字符串數值
代碼
public String getCellStringValue(HSSFCell cell) {
String cellValue = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
if(cellValue.trim().equals("")||cellValue.trim().length()<=0)
cellValue=" ";
break;
case HSSFCell.CELL_TYPE_NUMERIC:
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
cellValue=" ";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
default:
break;
}
return cellValue;
}
八、經常使用單元格邊框格式
虛線HSSFCellStyle.BORDER_DOTTED
實線HSSFCellStyle.BORDER_THIN
代碼
public static HSSFCellStyle getCellStyle(short type)
{
HSSFWorkbook wb = new HSSFWorkbook();
HSSFCellStyle style = wb.createCellStyle();
style.setBorderBottom(type);//下邊框
style.setBorderLeft(type);//左邊框
style.setBorderRight(type);//右邊框
style.setBorderTop(type);//上邊框
return style;
}
九、設置字體和內容位置
代碼
HSSFFont f = wb.createFont();
f.setFontHeightInPoints((short) 11);//字號
f.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);//加粗
style.setFont(f);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
style.setRotation(short rotation);//單元格內容的旋轉的角度
HSSFDataFormat df = wb.createDataFormat();
style1.setDataFormat(df.getFormat("0.00%"));//設置單元格數據格式
cell.setCellFormula(string);//給單元格設公式
style.setRotation(short rotation);//單元格內容的旋轉的角度
cell.setCellStyle(style);
十、插入圖片
論壇裏看到的
代碼
//先把讀進來的圖片放到一個ByteArrayOutputStream中,以便產生ByteArray
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
BufferedImage bufferImg = ImageIO.read(new File("ok.jpg"));
ImageIO.write(bufferImg,"jpg",byteArrayOut);
//讀進一個excel模版
FileInputStream fos = new FileInputStream(filePathName+"/stencil.xlt");
fs = new POIFSFileSystem(fos);
//建立一個工做薄
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
HSSFClientAnchor anchor = new HSSFClientAnchor(0,0,1023,255,(short) 0,0,(short)10,10);
patriarch.createPicture(anchor , wb.addPicture(byteArrayOut.toByteArray(),HSSFWorkbook.PICTURE_TYPE_JPEG));
十一、設置列自動換行
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setWrapText(true);
sheet.setDefaultColumnStyle((short)0, cellStyle);
設置列的寬度
sheet.setColumnWidth((short)0,(short)9000);
sheet.setDefaultColumnStyle((short)0, cellStyle);
與
sheet.setDefaultColumnWidth((short)70);衝突
只會換行 不會設置列寬
單元格拷貝示例:
package testpoi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
/**
* 將某SHEET頁中的某幾行復制到某SHEET頁的某幾行中。抱括被合併了的單元格。
*/
public class RowCopy {
/**
* @param args
* @throws IOException
* @throws FileNotFoundException
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) {
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(
"d://exlsample.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs);
// source爲源sheet 頁,target爲目標sheet頁
copyRows(wb, "source", "target", 5, 6, 20);
FileOutputStream fileOut = new FileOutputStream("d://exlsample.xls");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
System.out.println("Operation finished");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @param wb HSSFWorkbook
* @param pSourceSheetName 源sheet頁名稱
* @param pTargetSheetName 目標sheet頁名稱
* @param pStartRow 源sheet頁中的起始行
* @param pEndRow 源sheet頁中的結束行
* @param pPosition 目標sheet頁中的開始行
*/
public static void copyRows(HSSFWorkbook wb, String pSourceSheetName,
String pTargetSheetName, int intStartRow, int intEndRow, int intPosition) {
// EXECL中的行是從1開始的,而POI中是從0開始的,因此這裏要減1.
int pStartRow = intStartRow - 1;
int pEndRow = intEndRow - 1;
int pPosition = intPosition - 1;
HSSFRow sourceRow = null;
HSSFRow targetRow = null;
HSSFCell sourceCell = null;
HSSFCell targetCell = null;
HSSFSheet sourceSheet = null;
HSSFSheet targetSheet = null;
Region region = null;
int cType;
int i;
int j;
int targetRowFrom;
int targetRowTo;
if ((pStartRow == -1) || (pEndRow == -1)) {
return;
}
sourceSheet = wb.getSheet(pSourceSheetName);
targetSheet = wb.getSheet(pTargetSheetName);
System.out.println(sourceSheet.getNumMergedRegions());
// 拷貝合併的單元格
for (i = 0; i < sourceSheet.getNumMergedRegions(); i++) {
region = sourceSheet.getMergedRegionAt(i);
if ((region.getRowFrom() >= pStartRow)
&& (region.getRowTo() <= pEndRow)) {
targetRowFrom = region.getRowFrom() - pStartRow + pPosition;
targetRowTo = region.getRowTo() - pStartRow + pPosition;
region.setRowFrom(targetRowFrom);
region.setRowTo(targetRowTo);
targetSheet.addMergedRegion(region);
}
}
// 設置列寬
for (i = pStartRow; i <= pEndRow; i++) {
sourceRow = sourceSheet.getRow(i);
if (sourceRow != null) {
for (j = sourceRow.getLastCellNum(); j > sourceRow
.getFirstCellNum(); j--) {
targetSheet
.setColumnWidth(j, sourceSheet.getColumnWidth(j));
targetSheet.setColumnHidden(j, false);
}
break;
}
}
// 拷貝行並填充數據
for (; i <= pEndRow; i++) {
sourceRow = sourceSheet.getRow(i);
if (sourceRow == null) {
continue;
}
targetRow = targetSheet.createRow(i - pStartRow + pPosition);
targetRow.setHeight(sourceRow.getHeight());
for (j = sourceRow.getFirstCellNum(); j < sourceRow
.getPhysicalNumberOfCells(); j++) {
sourceCell = sourceRow.getCell(j);
if (sourceCell == null) {
continue;
}
targetCell = targetRow.createCell(j);
targetCell.setCellStyle(sourceCell.getCellStyle());
cType = sourceCell.getCellType();
targetCell.setCellType(cType);
switch (cType) {
case HSSFCell.CELL_TYPE_BOOLEAN:
targetCell.setCellValue(sourceCell.getBooleanCellValue());
System.out.println("--------TYPE_BOOLEAN:"
+ targetCell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
targetCell
.setCellErrorValue(sourceCell.getErrorCellValue());
System.out.println("--------TYPE_ERROR:"
+ targetCell.getErrorCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
// parseFormula這個函數的用途在後面說明
targetCell.setCellFormula(parseFormula(sourceCell
.getCellFormula()));
System.out.println("--------TYPE_FORMULA:"
+ targetCell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_NUMERIC:
targetCell.setCellValue(sourceCell.getNumericCellValue());
System.out.println("--------TYPE_NUMERIC:"
+ targetCell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
targetCell
.setCellValue(sourceCell.getRichStringCellValue());
System.out.println("--------TYPE_STRING:" + i
+ targetCell.getRichStringCellValue());
break;
}
}
}
}
/**
* POI對Excel公式的支持是至關好的,可是有一個問題,若是公式裏面的函數不帶參數,好比now()或today(),
* 那麼你經過getCellFormula()取出來的值就是now(ATTR(semiVolatile))和today(ATTR(semiVolatile)),
* 這樣的值寫入Excel是會出錯的,這也是我上面copyRow的函數在寫入公式前要調用parseFormula的緣由,
* parseFormula這個函數的功能很簡單,就是把ATTR(semiVolatile)刪掉。
* @param pPOIFormula
* @return
*/
private static String parseFormula(String pPOIFormula) {
final String cstReplaceString = "ATTR(semiVolatile)"; //$NON-NLS-1$
StringBuffer result = null;
int index;
result = new StringBuffer();
index = pPOIFormula.indexOf(cstReplaceString);
if (index >= 0) {
result.append(pPOIFormula.substring(0, index));
result.append(pPOIFormula.substring(index
+ cstReplaceString.length()));
} else {
result.append(pPOIFormula);
}
return result.toString();
}
}
參考地址:http://blog.163.com/wangfc123/blog/static/15746801200962332631573/