POI读写excel实例 (1)

来源:互联网 发布:js获取json字符串数据 编辑:程序博客网 时间:2024/06/03 21:47

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;}}


0 0
原创粉丝点击