写一个超级简单粗暴的小代码了,直接看吧
public static void createxlsFile(String filePath,String fileName,String suffix,Map<String,Object> colsLab,List<Map<String,Object>> data) {
String fileAbsolutePath=filePath+File.separator+fileName+"."+suffix;
File file = new File(fileAbsolutePath);
if (!file.exists()) {
file.mkdirs();
}
//创建工作薄对象
HSSFWorkbook workbook=new HSSFWorkbook();//这里也可以设置sheet的Name
//创建工作表对象
HSSFSheet sheet = workbook.createSheet();
//创建工作表的行
HSSFRow row = sheet.createRow(0);//设置第一行,从零开始
Set<Map.Entry<String, Object>> entries = colsLab.entrySet();
//相反数
int colSize=Math.negateExact(entries.size());
//标记每一个key对应的cell的列位置
Map<String,Integer> tag=new HashMap<>();
for (Map.Entry<String, Object> entry: entries) {
int cellPosition=colSize+entries.size();
row.createCell(cellPosition).setCellValue(entry.getValue().toString());//第
tag.put(entry.getKey(),cellPosition);
colSize++;
}
for(int i=0;i<data.size();i++){
HSSFRow dataRow = sheet.createRow(i+1);//设置第一行,从1开始
Set<Map.Entry<String, Object>> dataEntries = data.get(i).entrySet();
for (Map.Entry<String, Object> entry: dataEntries) {
//创建对应的列且赋值数据
HSSFCell cell = dataRow.createCell(tag.get(entry.getKey()));
cell.setCellValue(entry.getValue().toString());
}
}
//文档输出
try(FileOutputStream out = new FileOutputStream(fileAbsolutePath)){
workbook.write(out);
}catch (Exception e){
e.printStackTrace();
};
}
csv格式生成代码如下:参考其他人的改了关于值空情况与当前cell内容为大字段情况遇到的文本换行问题。传入数据格式与xls相同
public File createCSVFile(List exportData, LinkedHashMap map, String outPutPath,
String fileName) {
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
File file = new File(outPutPath);
if (!file.exists()) {
file.mkdirs();
}
//定义文件名格式并创建
csvFile = new File(outPutPath + fileName + ".csv");
file.createNewFile();
// UTF-8使正确读取分隔符","
//如果生产文件乱码,windows下用gbk,linux用UTF-8
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
csvFile), "UTF-8"), 1024);
// 写入文件头部
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator.hasNext(); ) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();
csvFileOutputStream.write((String) propertyEntry.getValue() != null ? (String) propertyEntry.getValue() : "");
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
csvFileOutputStream.newLine();
// 写入文件内容
for (Iterator iterator = exportData.iterator(); iterator.hasNext(); ) {
Object row = (Object) iterator.next();
if (ObjectUtil.isNull(row)) {
continue;
}
for (Iterator propertyIterator = map.entrySet().iterator(); propertyIterator
.hasNext(); ) {
java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator
.next();
Object cellData = ((Map) row).get(propertyEntry.getKey());
String str = ObjectUtil.isNotNull(cellData) ? String.valueOf(cellData) : "";
if (StringUtil.isBlank(str) || StringUtils.isEmpty(str)) {
str = "";
} else {
//ps:由于csv文件主要采用都好进行分割因此保证数据中\加双引号都好加双引号,换行符去掉。
str = str.replaceAll("\r|\n", "").replaceAll("\"", "\"\"").replaceAll(",", "\"\"");;
//字符串以0开头的数据在Excel中会自动去0,避免此问题用=""替换如0009->="0009"既可原样展示
if(str.startsWith("0")){
str="="+'"'+str+'"';
}
}
csvFileOutputStream.write(str);
if (propertyIterator.hasNext()) {
csvFileOutputStream.write(",");
}
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return csvFile;
}
对应的测试类如下
public static void main(String[] args) {
List exportData = new ArrayList<Map>();
Map row1 = new LinkedHashMap<String, String>();
row1.put("one", "shuju");
row1.put("two", "nn");
row1.put("three", "sf");
row1.put("four", "zhang");
exportData.add(row1);
row1 = new LinkedHashMap<String, String>();
row1.put("two", "啊我几个");
row1.put("one", "凡是敌人");
row1.put("four", "放到");
row1.put("three", "发");
exportData.add(row1);
LinkedHashMap map = new LinkedHashMap();
//设置列名
map.put("two", "第二列名称");
map.put("one", "第一列名称");
map.put("four", "第四列名称");
map.put("three", "第三列名称");
//这个文件上传到路径,可以配置在数据库从数据库读取,这样方便一些!
String path = "E:/";
//文件名=生产的文件名称+时间戳
String fileName = "文件导出";
createxlsFile(path,fileName,"xls",map,exportData );
// String fileName2 = file.getName();
// System.out.println("文件名称:" + fileName2);
}
记住啊,保证列顺序的话就用LinkedHashMap,over