您的位置:首页 > 其它

POI读写excel实例 (1)

2015-10-13 21:12 399 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: