java只能处理以xls结尾的excel文件,所以处理excel时,必须先把excel文件另存为.xls文件。
以下例子功能,对excel中所以cell进行判断。把cell中的回车符号转换为空格。
帮同事写的一个小工具。
以下例子功能,对excel中所以cell进行判断。把cell中的回车符号转换为空格。
帮同事写的一个小工具。
package com.jun.xie;
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class ClearEnter {
/**
* @param args
*/
public static void main(String[] args) {
ClearEnter test = new ClearEnter();
String path = "C:\\01\\test";
File file = new File(path);
File[] filelist = test.getFilelist(file);
for (File newfile : filelist) {
if (newfile.getName().endsWith("xls")) {
System.out.println(newfile.getName() + " is a xls file");
System.out.println("--start--");
test.doFile(newfile);
System.out.println("--end--");
}
}
}
private File[] getFilelist(File file) {
File[] list = null;
if (file.isDirectory()) {
list = file.listFiles();
}
return list;
}
private void doFile(File file) {
try {
Workbook wb = Workbook.getWorkbook(file);
// 打开一个文件的副本,并且指定数据写回到原文件
WritableWorkbook book = Workbook.createWorkbook(file, wb);
//循环编列sheet
for (int i = 0; i < book.getSheets().length; i++) {
WritableSheet sheet = book.getSheet(i);
//双重循环编列cell
for (int j = 0; j < sheet.getColumns(); j++) {
for (int k = 0; k < sheet.getRows(); k++) {
//取出cell中的值
Cell cell1 = sheet.getCell(j, k);
String result = cell1.getContents();
//把所有的回车符号转换为空格,并且重新写入到原来的cell中
if (result.indexOf("\n") != -1) {
System.out.println("hi");
System.out
.println("sheet name: " + sheet.getName());
System.out.println("第" + (k + 1) + "行 ---" + "第"
+ (j + 1) + "列进行了修改");
result = result.replaceAll("\n", " ");
try {
sheet.addCell(new Label(j, k, result));
} catch (RowsExceededException e) {
System.out.println("---------");
e.printStackTrace();
} catch (WriteException e) {
System.out.println("-+++++++++-");
e.printStackTrace();
}
} else {
continue;
}
}
}
}
book.write();
book.close();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}