前言
有个朋友需求将Excel中的数据进行行和列数据的转换,于是用Java写了个程序,通过文件流和算法进行转化
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
| package io.github.feiju12138;
import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List;
public class Format {
private static String dir = "./in/"; private static String outDir = "./out/";
public static void main(String[] args) throws Exception {
File rootDir = new File(dir); File rootOutDir = new File(outDir);
if (!rootDir.exists()) { rootDir.mkdir(); }
if (!rootOutDir.exists()) { rootOutDir.mkdir(); }
String[] filesList = rootDir.list(); for (String file : filesList) { List<String[]> list = new ArrayList<>(); BufferedReader in = new BufferedReader(new FileReader(dir + file)); String str; while ((str = in.readLine()) != null) { String[] rowString = str.split("\t"); list.add(rowString);
}
int row = 0; int col = 0;
for (String[] s : list) { if (s.length > row) { row = s.length; } } col = list.size();
String[][] arrOld = new String[col][row]; for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { String[] strings = list.get(i); arrOld[i][j] = strings[j]; } }
String[][] arrNew = new String[row][col];
for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { arrNew[j][i] = arrOld[i][j]; } }
String outStr = ""; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { outStr += arrNew[i][j] + "\t"; } outStr += "\n"; }
char[] arrC = new char[outStr.length()]; for (int i = 0; i < outStr.length(); i++) { char c = outStr.charAt(i); arrC[i] = c; }
Charset cs = Charset.forName("UTF-8"); CharBuffer cb = CharBuffer.allocate(arrC.length); cb.put(arrC); cb.flip(); ByteBuffer bb = cs.encode(cb); byte[] buff = bb.array();
FileOutputStream out = new FileOutputStream(outDir + file); out.write(buff, 0, buff.length);
System.out.println("文件<"+file+">转化完成,输出路径:"+ outDir + file);
in.close();
}
}
}
|
完成