Apache POIで作成した複数ExcelファイルをZIP圧縮する。

Excelファイルを動的に作成してそれを圧縮してみた。

Webとかで一括ファイルダウンロードとかの用途があると思う。
ググったらあるかなと思ったけども意外となかった・・・orz

で、とりあえず作成。
ソースはこんな感じ、エラー処理適当。

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

/*
 * Copyright 2009- kensir0u.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
/*
 * 作成日 (creation date)  :2009/02/24
 * パッケージ  (package name) :
 * ファイル名  (file name)    :CreateZip.java
 */

/**
 * <i>概要(abstract)</i>: Excelファイルを複数圧縮  .
 * <p>
 * Excelファイルを複数圧縮
 * 
 * 
 * @author kensir0u
 * @version 1.0
 * @since JDK 5.0
 * 
 */
public class CreateZip {

	public static void main(String[] args) {
		try {

			CreateZip cz = new CreateZip("日本語.zip");

			ByteArrayOutputStream baos = null;

			for (int i = 0; i < 20; i++) {
				baos = getFile("日本語" + i);
				cz.addFile("日本語" + i + ".xls", baos.toByteArray());
			}
			cz.zos.close();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static ByteArrayOutputStream getFile(String file) throws Exception {

		Workbook workbook = new HSSFWorkbook();

		Sheet sheet = workbook.createSheet();
		workbook.setSheetName(0, file);

		String value = "日本語";

		Row row = sheet.getRow(0);
		if (row == null) {
			row = sheet.createRow(0);
		}

		Cell cell = row.getCell((short) (0));
		if (cell == null) {
			cell = row.createCell((short) (0));
		}

		cell.setCellValue(value);

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		workbook.write(baos);

		return baos;
	}

	/** stream **/
	private ZipOutputStream zos = null;

	private CreateZip(String zipFileName) throws Exception {
		zos = new ZipOutputStream(new FileOutputStream(new File(zipFileName)));
		zos.setEncoding("MS932");
	}

	/*
	 * Webの場合はこのコンストラクタを利用。 
	 * 
	 * public CreateZip(HttpServletResponse response)throws Exception {
	 *     zos = new ZipOutputStream(response.getOutputStream());
	 * }
	 */
	private void addFile(String entryName, byte[] data) throws Exception {

		zos.putNextEntry(new ZipEntry(entryName));
		zos.write(data, 0, data.length);
		zos.closeEntry();

	}





}