자바 엑셀

3000 단어 기술 의 길
package com.xmg.excel;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import com.xmg.constants.ExcelConstant;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import net.sf.json.JSONArray;

public class ExcelTranslator {

	public static void main(String[] args) {
		String cfgFile = "test.xls";
		if (args.length > 0) {
			cfgFile = args[0];
		}
		new ExcelTranslator().translateFile(cfgFile);
		//new ExcelTranslator().test();
	}

	private void test() {
		JSONArray array1 = new JSONArray();
		array1.add(12);
		array1.add(22);
		JSONArray array2 = new JSONArray();
		array2.add(21);
		array2.add(22);
		JSONArray array = new JSONArray();
		array.add(array1);
		array.add(array2);
		System.out.println(array.toString());
	}
	
	
	Sheet sheet;
	Workbook book;

	private void translateFile(String cfgFile) {

		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		URL url = classLoader.getResource(cfgFile);
		try {
			book = Workbook.getWorkbook(new File(url.getFile()));
			sheet = book.getSheet(0);
			outputToJSON(sheet);
		} catch (BiffException | IOException e) {
			e.printStackTrace();
		}
	}

	private void outputToJSON(Sheet sheet2) throws IOException {
		JSONArray arr = new JSONArray();
		for (int i = ExcelConstant.DATA_START_INDEX; i < sheet.getRows(); i++) {
			JSONArray rowarr = new JSONArray();	
			for (int j = 0; j < sheet.getColumns(); j++) {
				Cell cell = sheet.getCell(j, i);
				rowarr.add(cell.getContents());
			}
			arr.add(rowarr);
		}
		writeToFile(arr.toString(),".json");
	}

	public void outputToTxt(Sheet sheet) throws IOException {
		StringBuilder builder = new StringBuilder();
		for (int i = ExcelConstant.DATA_START_INDEX; i < sheet.getRows(); i++) {

			for (int j = 0; j < sheet.getColumns(); j++) {
				Cell cell = sheet.getCell(j, i);
				builder.append(cell.getContents() + "|");
			}
			builder.append("\r
"); } writeToFile(builder.toString(),".txt"); } public void writeToFile(String info,String filePostfix) throws IOException { String path = ExcelConstant.GENERATE_TXT_LOCATION + sheet.getName() + filePostfix; BufferedWriter bw = null; try { FileOutputStream out = new FileOutputStream(path, true);// true, : , , false bw = new BufferedWriter(new OutputStreamWriter(out, "GBK")); bw.write(info += "\r
");// bw.flush(); } catch (Exception e) { e.printStackTrace(); } finally { bw.close(); } } public void printOutContent(Sheet sheet) { for (int i = ExcelConstant.DATA_START_INDEX; i < sheet.getRows(); i++) { for (int j = 0; j < sheet.getColumns(); j++) { Cell cell = sheet.getCell(j, i); System.out.print(cell.getContents() + "|"); } System.out.println(); } } }

좋은 웹페이지 즐겨찾기