疑惑
//创建文件
File file = new File("E:/test2.xls");
file.createNewFile();
这个createNewFile()真的可以创建任何格式的文件吗?
答案是是可以的。
参考下面这个链接:
http://www.debugease.com/j2se/288080.html
可以创建任何格式文件,但文件格式不中是通过扩展名来区分的,关键在于文件的数据格式。每个类型的文件有自己的文件格式。如果你创建一个 xxx.doc 而只往里写几个文本,用word打开肯定格式错误。
理解
说一下我对Excel文件的理解,版本有xls和xlsx。工作簿就是Excel文件。
表格是工作簿中的中心结构,是用户完成大部分电子表格工作的地方。最常见的表格类型是工作表,表示为单元格网格。(Sheet)
Row:行
Cell:单元格,工作表单元格可以包含文本,数字,日期和公式。单元格也可以格式化。
创建Excel(xls)
废话不多说,直接上代码:
方式一:使用HSSFWorkbook
public class CreateFileTest3 {
public static void main(String[] args) throws IOException, RowsExceededException, WriteException {
//创建文件
File file = new File("E:/test2.xls");
file.createNewFile();
//向文件写数据
OutputStream outputStream = new FileOutputStream ( file );// 创建工作薄
HSSFWorkbook workBook = new HSSFWorkbook();
Sheet sheet = workBook.createSheet("First Sheet");
Row row = sheet.createRow(0);
for (int i = 0; i < 3; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(i+"(* ̄︶ ̄");
}
workBook.write(outputStream);
}
}
方式二:
//创建文件
File file = new File("E:/test1.xls");//如果改成xlsx也会报错,不明白原因,研究中....
file.createNewFile();
//向文件写数据
OutputStream outputStream = new FileOutputStream ( file );// 创建工作薄
WritableWorkbook writableWorkbook = jxl.Workbook.createWorkbook ( outputStream );
// WritableWorkbook writableWorkbook = jxl.Workbook.createWorkbook(file);
WritableSheet sheet = writableWorkbook.createSheet ( "First sheet", 0 );// 创建新的一页
for (int i = 0; i < 3; i++) {
Label label = new Label ( i, 0, i+"(* ̄︶ ̄)" ); // 第一个参数是单元格所在列,第二个参数是单元格所在行,第三个参数是值
sheet.addCell ( label );
}
writableWorkbook.write (); // 加入到文件中
writableWorkbook.close (); // 关闭文件,释放资源
说实话,查了很多资料,用Java到最后也没能实现xlsx文件的创建,新建:
XSSFWorkbook workBook = new XSSFWorkbook();
就会报错,不清楚什么问题,希望大神指点,感激不尽。
读Excel
//读
FileInputStream in = new FileInputStream(file);
Workbook wb = null;
wb = new HSSFWorkbook ( in );
Sheet s = wb.getSheet("First sheet");
int totalRows = s.getPhysicalNumberOfRows();
for (int i = 0; i < totalRows; i++) {
Row r = s.getRow(i);
int cells = r.getPhysicalNumberOfCells();
for (int j = 0; j < cells; j++) {
System.out.println(r.getCell(j));
}
}
这就是我今天研究的内容了,如有错误,欢迎指正,谢谢~~~
[1] :http://poi.apache.org/apidocs/dev/org/apache/poi/ss/usermodel/Workbook.html#createSheet--
[2]:https://www.jianshu.com/p/1bfdd92bd385?utm_campaign=maleskine&utm_content=note&utm_medium=seo_notes&utm_source=recommendation
[3]: http://www.cnblogs.com/wuxinrui/archive/2011/03/20/1989326.html
[4]: http://www.debugease.com/j2se/288080.html