POIでEXCELを編集するサンプル

Excel2003以前のバージョン(xls)を読み込む方法
XML形式(xlsx)を読み込む方法
パスワードがかかっているExcelファイルを読み込み、パスワードをかけて保存する方法
  1. import java.io.File;
  2. import java.io.FileInputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.security.GeneralSecurityException;
  8. import org.apache.poi.POIXMLException;
  9. import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
  10. import org.apache.poi.hssf.usermodel.HSSFWorkbook;
  11. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  12. import org.apache.poi.openxml4j.opc.OPCPackage;
  13. import org.apache.poi.openxml4j.opc.PackageAccess;
  14. import org.apache.poi.poifs.crypt.Decryptor;
  15. import org.apache.poi.poifs.crypt.EncryptionInfo;
  16. import org.apache.poi.poifs.crypt.Encryptor;
  17. import org.apache.poi.poifs.filesystem.POIFSFileSystem;
  18. import org.apache.poi.ss.usermodel.Cell;
  19. import org.apache.poi.ss.usermodel.Row;
  20. import org.apache.poi.ss.usermodel.Sheet;
  21. import org.apache.poi.ss.usermodel.Workbook;
  22. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  23. /**
  24. * Apache POI(Ver3.11)を使用して、Excelファイルを読み込み、上書き保存するサンプル。
  25. * パスワードがかかっているExcelにも対応。
  26. * xls、xlsxの両方に対応。
  27. * POIをダウンロードし、解凍された下記JARファイルをビルドパスに追加する必要あり。
  28. * poi-3.11-20141221.jar
  29. * poi-excelant-3.11-20141221
  30. * poi-ooxml-3.11-20141221.jar
  31. * poi-ooxml-schemas-3.11-20141221.jar
  32. * poi-scratchpad-3.11-20141221.jar
  33. * xmlbeans-2.6.0.jar
  34. */
  35. public class ExcelSample {
  36.     public static void main(String[] args) {
  37.         try {
  38.             // xlsx形式、またはxlsm形式のパスワード付きExcelファイルを開く&保存する場合
  39.             excelOpenXlsxPassword("C:/Test/testPass.xlsx", "password");
  40.             // xls形式のパスワード付きExcelファイルを開く&保存する場合
  41.             excelOpenXlsPassword("C:/Test/testPass.xls", "password");
  42.             // パスワードがかかっていないExcelファイルを開く場合(xls、xlsxの両方に対応)
  43.             excelOpen("C:/Test/test.xls");
  44.         }
  45.         catch (Exception e) {
  46.             e.printStackTrace();
  47.         }
  48.     }
  49.     /**
  50.      * パスワード付きExcelファイルの読み込み&書き込み。
  51.      * Excel2003より新しい形式(xlsx、xlsm)専用の処理。
  52.      * 参考:https://poi.apache.org/encryption.html
  53.      * @param filePath Excelファイルのフルパス
  54.      * @param password パスワード
  55.      * @throws IOException
  56.      */
  57.     public static void excelOpenXlsxPassword(String filePath, String password) throws IOException {
  58.         FileInputStream fi = null;
  59.         POIFSFileSystem fileSystem = null;
  60.         InputStream is = null;
  61.         Workbook wb = null;
  62.         try {
  63.             fi = new FileInputStream(filePath);
  64.             fileSystem = new POIFSFileSystem(fi);
  65.             EncryptionInfo info = new EncryptionInfo(fileSystem);
  66.             Decryptor d = Decryptor.getInstance(info);
  67.             if (d.verifyPassword(password) == false) {
  68.                 System.out.println("パスワードを解除出来ませんでした。");
  69.                 return;
  70.             }
  71.             is = d.getDataStream(fileSystem);
  72.             wb = new XSSFWorkbook(is);
  73.             // セルの値が読めているか確認
  74.             Sheet sheet = wb.getSheet("Sheet1");
  75.             Row row = sheet.getRow(0);
  76.             Cell cell = row.getCell(0);
  77.             String val = cell.getStringCellValue();
  78.             System.out.println("セルの値 = " + val);
  79.             // 書き込みが出来るか確認
  80.             Cell cell2 = row.createCell(1);
  81.             cell2.setCellValue("テスト");
  82.             // 新規ファイルとして保存(この時点ではパスワード無し)
  83.             wb.write(new FileOutputStream(filePath));
  84.             POIFSFileSystem fs = new POIFSFileSystem();
  85.             Encryptor enc = info.getEncryptor();
  86.             // 既存と同じパスワードを設定(新しいパスワードでも問題無し)
  87.             enc.confirmPassword(password);
  88.             OPCPackage opc = OPCPackage.open(new File(filePath), PackageAccess.READ_WRITE);
  89.             OutputStream os = enc.getDataStream(fs);
  90.             opc.save(os);
  91.             opc.close();
  92.             // パスワード付きで上書き保存
  93.             FileOutputStream fos = new FileOutputStream(filePath);
  94.             fs.writeFilesystem(fos);
  95.             fos.close();
  96.         }
  97.         catch (GeneralSecurityException | IOException | InvalidFormatException e) {
  98.             e.printStackTrace();
  99.         }
  100.         finally {
  101.             if (wb != null) {
  102.                 wb.close();
  103.             }
  104.             if (is != null) {
  105.                 is.close();
  106.             }
  107.             if (fi != null) {
  108.                 fi.close();
  109.             }
  110.         }
  111.     }
  112.     /**
  113.      * パスワード付きExcelファイルの読み込み&書き込み。
  114.      * Excel2003以前の形式(xls)専用の処理。
  115.      * 参考:https://poi.apache.org/encryption.html
  116.      * @param filePath Excelファイルのフルパス
  117.      * @param password パスワード
  118.      * @throws IOException
  119.      */
  120.     public static void excelOpenXlsPassword(String filePath, String password) throws IOException {
  121.         FileInputStream fi = null;
  122.         HSSFWorkbook wb = null;
  123.         try {
  124.             fi = new FileInputStream(filePath);
  125.             Biff8EncryptionKey.setCurrentUserPassword(password);
  126.             wb = new HSSFWorkbook(fi);
  127.             // セルの値が読めているか確認
  128.             Sheet sheet = wb.getSheet("Sheet1");
  129.             Row row = sheet.getRow(0);
  130.             Cell cell = row.getCell(0);
  131.             String val = cell.getStringCellValue();
  132.             System.out.println("セルの値 = " + val);
  133.             // 書き込みが出来るか確認
  134.             Cell cell2 = row.createCell(1);
  135.             cell2.setCellValue("テスト");
  136.             // パスワードを設定。第二引数(ユーザー名)は任意で指定。
  137.             wb.writeProtectWorkbook(password, "");
  138.             // 上書き保存
  139.             wb.write(new FileOutputStream(filePath));
  140.         }
  141.         catch (IOException e) {
  142.             e.printStackTrace();
  143.         }
  144.         finally {
  145.             if (wb != null) {
  146.                 wb.close();
  147.             }
  148.             if (fi != null) {
  149.                 fi.close();
  150.             }
  151.         }
  152.     }
  153.     /**
  154.      * Excelファイルの読み込み。
  155.      * xls、xlsx両方に対応。
  156.      * @param filePath Excelファイルのフルパス
  157.      * @throws IOException
  158.      */
  159.     public static void excelOpen(String filePath) throws IOException {
  160.         FileInputStream fi = null;
  161.         Workbook wb = null;
  162.         try {
  163.             try {
  164.                 fi = new FileInputStream(filePath);
  165.                 // Excel2003より新しいバージョンとしてファイルを開く
  166.                 wb = new XSSFWorkbook(fi);
  167.             }
  168.             catch (POIXMLException e) {
  169.                 try {
  170.                     fi.close();
  171.                     fi = new FileInputStream(filePath);
  172.                     // Excel2003以前のバージョンとしてファイルを開く
  173.                     wb = new HSSFWorkbook(fi);
  174.                 }
  175.                 catch (IOException e1) {
  176.                     throw e1;
  177.                 }
  178.             }
  179.             catch (IOException e) {
  180.                 throw e;
  181.             }
  182.             // セルの値が読めているか確認
  183.             Sheet sheet = wb.getSheet("Sheet1");
  184.             Row row = sheet.getRow(0);
  185.             Cell cell = row.getCell(0);
  186.             String val = cell.getStringCellValue();
  187.             System.out.println("セルの値 = " + val);
  188.         }
  189.         finally {
  190.             if (wb != null) {
  191.                 wb.close();
  192.             }
  193.             if (fi != null) {
  194.                 fi.close();
  195.             }
  196.         }
  197.     }
  198. }
JAVAソースのダウンロード(UTF-8です)

戻る