62,614
社区成员
发帖
与我相关
我的任务
分享
*该类的功能是某一份execl文件,有一个单元格的值有多个,在其它单元格不变的情况下,分为多行
* 效果如:
* 姓名 年龄 爱好
* lei 20 游泳,睡觉
* lei2 20 玩电脑
* 变为:
* 姓名 年龄 爱好
* lei 20 游泳
* lei 20 睡觉
* lei2 20 玩电脑
*
* */
public class OneRowToMany {
public static void main(String[] args) {
//源execl文件
String fromexecl="D:\\xxx.xlsx";
//写入到的txt文件,以,分割
String totxt="D:\\xxx.txt";
try {
String[][] str=ExeclHelper.poiReader(fromexecl);
int rownum=str.length;
int columnum=str[0].length;
String result = "";
//从第1行开始读取数据,第0行是表头
for(int i=1;i<rownum;i++){
String rows = "";
//获取除了最后一行之外其他单元格的数据
for(int j=0;j<columnum-1;j++){
//获取每行的其他值
rows=rows+str[i][j]+",";
}
System.out.println(str[i][columnum-1]);
String brandname=str[i][columnum-1];
//如果正常的以" "分割的,执行,否侧,跳过
if(brandname.contains(" ")){
String[] brand=brandname.split(" ");
for(int k=0;k<brand.length;k++){
result=result+rows+brand[k]+"\n";
}
}else{
result=result+rows+"null"+"\n";
}
WriteHelper.writeToTxt(totxt, result);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void poiWrite(String[][] str,String filepath){
InputStream inp;
ifexist(filepath);
try {
inp = new FileInputStream(filepath);
int rownum=str.length;
int columnum=str[0].length;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
for(int i=0;i<rownum;i++){
//System.out.println("i:"+i);
Row row = sheet.createRow(i);
for(int j=0;j<columnum;j++){
/*System.out.println("j:"+j); */
Cell cell=row.createCell(j);
//设置格式
cell.setCellType(Cell.CELL_TYPE_STRING);
//设置值
cell.setCellValue(str[i][j]);
}
}
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream(filepath);
wb.write(fileOut);
fileOut.close();
inp.close();
System.out.println("写入完成");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//传入文件的地址,判断文件是否存在,如果不存在的话创建该文件
public static void ifexist(String path){
try {
File file=new File(path);
if(!file.exists()){
System.out.println("文件不存在,创建该文件,文件地址为:"+path);
file.createNewFile();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class WriteHelper {
public static void writeToTxt(String file,String str){
File f=new File(file);
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file);
PrintWriter pw=new PrintWriter(fw);
pw.print(str);
pw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("记录文件写入已完成,文件地址为"+file);
}
}