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; } }
相关文章推荐
- 解决:子元素设置margin-top,父元素也受影响的问题
- SetThreadAffinityMask的用法
- 【队列项目2 - 建立链队算法库——第7周】
- hdu 3727 Jewel(主席树学习第四弹)
- Swift 播放视频
- python中的pandas包的数据清洗能力
- Cpp--字符串快速查找运用
- 【bzoj3174】【TJOI2013】【拯救小矮人】【贪心+dp】
- ZOJ 1136 Multiply
- spring scope
- C++中的static关键字
- JS的运算
- Swift 原生网络通信
- [LeetCode-80] Remove Duplicates from Sorted Array II
- 《剑指Offer》面试题:找出数组中有3个出现一次的数字
- python中knn算法实现
- C++程序员学习发展方向分析和指导(C++入门学习指导建议必看)
- hdu 5501 The Highest Mark(变形01背包)
- JavaScript 数据类型、运算符
- postgresql导出sql执行结果到文件的方法(转)