1. 程式人生 > >POI讀寫excel例項 (1)

POI讀寫excel例項 (1)

excel讀入進行單元格賦值

package testPOI;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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 TestExcel {

	public static void main(String[] args) throws IOException {
	    Workbook wb = new HSSFWorkbook();           // or new XSSFWorkbook();
        FileInputStream io = null;
        try {
            io = new FileInputStream("d:/workbook.xlsx");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            wb = new XSSFWorkbook(io);
            io.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        Sheet sheet1 = wb.getSheetAt(0);
        Row row = sheet1.getRow(0);
        
        int copyStartColumnIndex = 0;
        int coyColumnCount = 3;
        int columnEndIndex = row.getLastCellNum();
        
        for (int i = columnEndIndex; i > copyStartColumnIndex + coyColumnCount - 1; i--) {	
        	Cell cellNew = TestExcel.getCell(row, i + coyColumnCount);
        	Cell cellOld = TestExcel.getCell(row, i);
        	TestExcel.copyCell(cellNew, cellOld, sheet1);
        }
        for (int i = copyStartColumnIndex; i < coyColumnCount; i++) {
        	Cell cellNew = TestExcel.getCell(row, i + coyColumnCount);
        	Cell cellOld = TestExcel.getCell(row, i);
        	TestExcel.copyCell(cellNew, cellOld, sheet1);
        }
        

	    FileOutputStream fileOut = new FileOutputStream("d:/workbook.xlsx");
	    wb.write(fileOut);
	    fileOut.close();
	}
	
	public static void copyCell(Cell newCell, Cell oldCell, Sheet sheet) {
		CellStyle oldStyle = oldCell.getCellStyle();
		newCell.setCellStyle(oldStyle);
		newCell.setCellValue(oldCell.getStringCellValue());
		sheet.setColumnWidth(newCell.getColumnIndex(), sheet.getColumnWidth(oldCell.getColumnIndex()));
	}
	
	public static Cell getCell (Row row, int columnNum) {
		Cell cell = row.getCell(columnNum);
		if (cell == null) {
			cell = row.createCell(columnNum);
		}
		return cell;
	}
}