用java从0生成一个简单的excel
样例
自己写了一个把txt格式的文件中数据读取,然后输出到表格中的程序,用到了上面说的所有操作,当然现在会的也就这么一点点了,还蛮好玩的,代码送上:
import org.apache.poi.hssf.usermodel.*;//基础的表格操作
import java.io.*;//屏幕输出和文件输出
import java.util.Calendar;//日历包
public class Main {
public static String [] DayArray;
public static String [] TimeArray;
public static String [][] PerList=new String[6][];
public static void main(String[] args)throws IOException{
Main.ReadFile();
Main.OutputFile();
for(String sting:DayArray){
System.out.println(sting);
}
for(String string:TimeArray){
System.out.println(string);
}
for(int i=0;i<TimeArray.length;i++){
for(int j=0;j<DayArray.length;j++){
if(j!=0)
System.out.print(" ");
System.out.print(PerList[i][j]);
}
System.out.println();
}
}
public static void ReadFile()throws IOException{
InputStream in=new FileInputStream("D:\\排班数据管理\\Basis.txt");
String line;
BufferedReader reader=new BufferedReader(new InputStreamReader(in,"GBK"));
line=reader.readLine();
DayArray =line.split("\\s+");
line=reader.readLine();
TimeArray=line.split("\\s+");
Calendar calendar=Calendar.getInstance();
calendar.set(2018,11,9);
in=new FileInputStream("D:\\排班数据txt\\"+
(calendar.get(calendar.MONTH)+1)+"月"+
calendar.get(calendar.DATE)+ "日数据.txt");
reader=new BufferedReader(new InputStreamReader(in,"GBK"));
reader.readLine();
reader.readLine();
for(int i=0;i<TimeArray.length;i++){
line=reader.readLine();
PerList[i]=line.split("\\s+");
}
reader.close();
}
public static void OutputFile()throws IOException{
HSSFWorkbook wb=new HSSFWorkbook();
HSSFSheet sheet=wb.createSheet("值班表");
HSSFRow row=sheet.createRow(0);
HSSFCell cell;
int index=1;
for(String string:DayArray){
cell=row.createCell(index);
cell.setCellValue(string);
index++;
}
for(int i=0;i<TimeArray.length;i++){
row=sheet.createRow(i+1);
cell=row.createCell(0);
cell.setCellValue(TimeArray[i]);
for(int j=0;j<DayArray.length;j++){
cell=row.createCell(j+1);
cell.setCellValue(PerList[i][j]);
}
}
FileOutputStream outputStream=new FileOutputStream("D:\\test值班表.xls");
wb.write(outputStream);
outputStream.close();
}
}
效果如下:(已打码)
后记
API大法好,用起来真的很舒服了,目前就学了这么一点,更多骚操作大家可以自己网上找找,查POI就可以了,过程中有不理解的欢迎留言讨论哈~
2018/12/12 16:51:27