大家好,又见面了,我是你们的朋友全栈君。
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\n");
}
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\n");// 换行
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();
}
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/130772.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...