java poi excel操作示例

使用poi3.9版本使用的示例

参考:http://poi.apache.org/spreadsheet/quick-guide.html

[java]  view plain copy
  1. import java.io.FileOutputStream;  
  2. import java.io.IOException;  
  3. import java.util.Calendar;  
  4. import java.util.Date;  
  5. import java.util.Iterator;  
  6.   
  7. import org.apache.poi.hssf.usermodel.HSSFHeader;  
  8. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  9. import org.apache.poi.ss.usermodel.Cell;  
  10. import org.apache.poi.ss.usermodel.CellStyle;  
  11. import org.apache.poi.ss.usermodel.ClientAnchor;  
  12. import org.apache.poi.ss.usermodel.Comment;  
  13. import org.apache.poi.ss.usermodel.CreationHelper;  
  14. import org.apache.poi.ss.usermodel.DataFormat;  
  15. import org.apache.poi.ss.usermodel.DateUtil;  
  16. import org.apache.poi.ss.usermodel.Drawing;  
  17. import org.apache.poi.ss.usermodel.Font;  
  18. import org.apache.poi.ss.usermodel.Header;  
  19. import org.apache.poi.ss.usermodel.Name;  
  20. import org.apache.poi.ss.usermodel.RichTextString;  
  21. import org.apache.poi.ss.usermodel.Row;  
  22. import org.apache.poi.ss.usermodel.Sheet;  
  23. import org.apache.poi.ss.usermodel.Workbook;  
  24. import org.apache.poi.ss.util.CellRangeAddress;  
  25. import org.apache.poi.ss.util.CellReference;  
  26. import org.apache.poi.xssf.usermodel.XSSFWorkbook;  
  27.   
  28. //http://poi.apache.org/spreadsheet/quick-guide.html  
  29. public class ExcelParseUtil {  
  30.   
  31.     public static void test() throws IOException {  
  32.         Workbook wb = new HSSFWorkbook();  
  33.         FileOutputStream fileOut = new FileOutputStream(  
  34.                 "E:\\logs\\workbook.xls");  
  35.         Sheet sheet1 = wb.createSheet("new sheet");  
  36.         Sheet sheet2 = wb.createSheet("second sheet");  
  37.   
  38.         // 设置sheet的标题  
  39.         Header header = sheet1.getHeader();  
  40.         header.setCenter("Center Header");  
  41.         header.setLeft("Left Header");  
  42.         header.setRight(HSSFHeader.font("Stencil-Normal""Italic")  
  43.                 + HSSFHeader.fontSize((short16)  
  44.                 + "Right w/ Stencil-Normal Italic font and size 16");  
  45.   
  46.         // 合并单元格  
  47.         sheet1.groupRow(514);  
  48.         sheet1.groupRow(714);  
  49.         sheet1.groupRow(1619);  
  50.   
  51.         sheet1.groupColumn((short4, (short7);  
  52.         sheet1.groupColumn((short9, (short12);  
  53.         sheet1.groupColumn((short10, (short11);  
  54.   
  55.         sheet1.addMergedRegion(new CellRangeAddress(1// first row (0-based)  
  56.                 1// last row (0-based)  
  57.                 1// first column (0-based)  
  58.                 2 // last column (0-based)  
  59.         ));  
  60.   
  61.         // 设置图片  
  62.         // Create the drawing patriarch. This is the top level container for all  
  63.         // shapes.  
  64.         // Drawing drawing = sheet1.createDrawingPatriarch();  
  65.         //  
  66.         // //add a picture shape  
  67.         // ClientAnchor anchor = helper.createClientAnchor();  
  68.         // //set top-left corner of the picture,  
  69.         // //subsequent call of Picture#resize() will operate relative to it  
  70.         // anchor.setCol1(3);  
  71.         // anchor.setRow1(2);  
  72.         // Picture pict = drawing.createPicture(anchor, pictureIdx);  
  73.         //  
  74.         // //auto-size picture relative to its top-left corner  
  75.         // pict.resize();  
  76.   
  77.         String sname = "TestSheet", cname = "TestName", cvalue = "TestVal";  
  78.         Name namedCell = wb.createName();  
  79.         namedCell.setNameName(cname);  
  80.         String reference = sname + "!A1:A1"// area reference  
  81.         namedCell.setRefersToFormula(reference);  
  82.   
  83.         // 2. create named range for a single cell using cellreference  
  84.         // Name namedCel2 = wb.createName();  
  85.         // namedCel2.setNameName(cname);  
  86.         // reference = sname+"!A1"; // cell reference  
  87.         // namedCel2.setRefersToFormula(reference);  
  88.         //  
  89.         // // 3. create named range for an area using AreaReference  
  90.         // Name namedCel3 = wb.createName();  
  91.         // namedCel3.setNameName(cname);  
  92.         // reference = sname+"!A1:C5"; // area reference  
  93.         // namedCel3.setRefersToFormula(reference);  
  94.         //  
  95.         // // 4. create named formula  
  96.         // Name namedCel4 = wb.createName();  
  97.         // namedCel4.setNameName("my_sum");  
  98.         // namedCel4.setRefersToFormula("SUM(sname+!$I$2:$I$6)");  
  99.   
  100.         // Note that sheet name is Excel must not exceed 31 characters  
  101.         // and must not contain any of the any of the following characters:  
  102.         // 0x0000  
  103.         // 0x0003  
  104.         // colon (:)  
  105.         // backslash (\)  
  106.         // asterisk (*)  
  107.         // question mark (?)  
  108.         // forward slash (/)  
  109.         // opening square bracket ([)  
  110.         // closing square bracket (])  
  111.   
  112.         // You can use  
  113.         // org.apache.poi.ss.util.WorkbookUtil#createSafeSheetName(String  
  114.         // nameProposal)}  
  115.         // for a safe way to create valid names, this utility replaces invalid  
  116.         // characters with a space (' ')"  
  117.   
  118.         //设置单元格值  
  119.         // Create a row and put some cells in it. Rows are 0 based.  
  120.         Row row = sheet1.createRow((short0);  
  121.         // Create a cell and put a value in it.  
  122.         Cell cell = row.createCell(0);  
  123.         cell.setCellValue(1);  
  124.   
  125.         // Or do it on one line.  
  126.         row.createCell(1).setCellValue(1.2);  
  127.         row.createCell(2).setCellValue("This is a string");  
  128.         row.createCell(3).setCellValue(true);  
  129.   
  130.         Row row2 = sheet2.createRow(0);  
  131.   
  132.         // Create a cell and put a date value in it. The first cell is not  
  133.         // styled  
  134.         // as a date.  
  135.         Cell cell2 = row2.createCell(0);  
  136.         cell2.setCellValue(new Date());  
  137.   
  138.         // we style the second cell as a date (and time). It is important to  
  139.         // create a new cell style from the workbook otherwise you can end up  
  140.         // modifying the built in style and effecting not only this cell but  
  141.         // other cells.  
  142.         //设置单元格日期格式  
  143.         CellStyle cellStyle = wb.createCellStyle();  
  144.         DataFormat format = wb.createDataFormat();  
  145.         cellStyle.setDataFormat(format.getFormat("yyyy/mm/dd"));  
  146.         // style.setDataFormat(format.getFormat("#,##0.0000"));  
  147.   
  148.         //设置单元格字体  
  149.         Font font = wb.createFont();  
  150.         font.setFontHeightInPoints((short24);  
  151.         font.setFontName("Courier New");  
  152.         font.setItalic(true);  
  153.         font.setStrikeout(true);  
  154.         font.setBoldweight(Font.BOLDWEIGHT_BOLD);  
  155.   
  156.         cellStyle.setFont(font);  
  157.         cellStyle.setWrapText(true);  
  158.   
  159.         cell2 = row2.createCell(1);  
  160.         cell2.setCellValue(new Date());  
  161.         cell2.setCellStyle(cellStyle);  
  162.   
  163.         // you can also set date as java.util.Calendar  
  164.         cell2 = row2.createCell(2);  
  165.         cell2.setCellValue(Calendar.getInstance());  
  166.         cell2.setCellStyle(cellStyle);  
  167.   
  168.         // 註釋  
  169.         // Create the comment and set the text+author  
  170.         CreationHelper factory = wb.getCreationHelper();  
  171.         // When the comment box is visible, have it show in a 1x3 space  
  172.         ClientAnchor anchor = factory.createClientAnchor();  
  173.         anchor.setCol1(cell.getColumnIndex());  
  174.         anchor.setCol2(cell.getColumnIndex() + 1);  
  175.         anchor.setRow1(row.getRowNum());  
  176.         anchor.setRow2(row.getRowNum() + 3);  
  177.         Drawing drawing = sheet1.createDrawingPatriarch();  
  178.         Comment comment = drawing.createCellComment(anchor);  
  179.         RichTextString str = factory.createRichTextString("Hello, World!");  
  180.         comment.setString(str);  
  181.         comment.setAuthor("Apache POI");  
  182.   
  183.         // Assign the comment to the cell  
  184.         cell.setCellComment(comment);  
  185.   
  186.         // Hyperlink link = createHelper.createHyperlink(Hyperlink.LINK_URL);  
  187.         // link.setAddress("http://poi.apache.org/");  
  188.         // cell.setHyperlink(link);  
  189.         // cell.setCellStyle(cellStyle);  
  190.   
  191.         Row row3 = sheet2.createRow((short2);  
  192.         row3.createCell(0).setCellValue(1.1);  
  193.         row3.createCell(1).setCellValue(new Date());  
  194.         row3.createCell(2).setCellValue(Calendar.getInstance());  
  195.         row3.createCell(3).setCellValue("a string");  
  196.         row3.createCell(4).setCellValue(true);  
  197.         row3.createCell(5).setCellType(Cell.CELL_TYPE_ERROR);  
  198.   
  199.         //获取sheet的每个单元格的值  
  200.         Sheet sheet = wb.getSheetAt(0);  
  201.         for (Iterator<Row> rit = sheet.rowIterator(); rit.hasNext();) {  
  202.             Row row4 = rit.next();  
  203.             for (Iterator<Cell> cit = row4.cellIterator(); cit.hasNext();) {  
  204.                 Cell cell4 = cit.next();  
  205.                 // do something here  
  206.             }  
  207.         }  
  208.   
  209.         Sheet sheet5 = wb.getSheetAt(1);  
  210.         for (Row row5 : sheet5) {  
  211.             for (Cell cell5 : row5) {  
  212.                 CellReference cellRef = new CellReference(row5.getRowNum(),  
  213.                         cell5.getColumnIndex());  
  214.                 System.out.print(cellRef.formatAsString());  
  215.                 System.out.print(" - ");  
  216.   
  217.                 switch (cell5.getCellType()) {  
  218.                 case Cell.CELL_TYPE_STRING:  
  219.                     System.out.println(cell5.getRichStringCellValue()  
  220.                             .getString());  
  221.                     break;  
  222.                 case Cell.CELL_TYPE_NUMERIC:  
  223.                     if (DateUtil.isCellDateFormatted(cell5)) {  
  224.                         System.out.println(cell5.getDateCellValue());  
  225.                     } else {  
  226.                         System.out.println(cell5.getNumericCellValue());  
  227.                     }  
  228.                     break;  
  229.                 case Cell.CELL_TYPE_BOOLEAN:  
  230.                     System.out.println(cell5.getBooleanCellValue());  
  231.                     break;  
  232.                 case Cell.CELL_TYPE_FORMULA:  
  233.                     System.out.println(cell5.getCellFormula());  
  234.                     break;  
  235.                 default:  
  236.                     System.out.println();  
  237.                 }  
  238.             }  
  239.         }  
  240.   
  241.         wb.write(fileOut);  
  242.         fileOut.close();  
  243.     }  
  244.   
  245.     public void test2() throws IOException {  
  246.         Workbook wb = new XSSFWorkbook();  
  247.         FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");  
  248.         wb.write(fileOut);  
  249.         fileOut.close();  
  250.     }  
  251.   
  252.     public static void main(String[] args) throws IOException {  
  253.         test();  
  254.     }  
  255.   
  256. }  

输出:

[java]  view plain copy
  1. A1 - 41258.65454309028  
  2. B1 - Sat Dec 15 15:42:32 CST 2012  
  3. C1 - Sat Dec 15 15:42:32 CST 2012  
  4. A3 - 1.1  
  5. B3 - 41258.65454322917  
  6. C3 - 41258.65454322917  
  7. D3 - a string  
  8. E3 - true  
  9. F3 -   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值