在项目中使用easyExcel做模板校验的时候,同样的字符串equals判断为false。这是为什么,有没有知道的,我百思不得其解
前面有个 ! 号 你看到m没
在使用 EasyExcel 进行模板校验时,如果相同的字符串进行 equals 比较结果为 false,可能是以下几个原因:
String str1 = "abc ";
String str2 = "abc";
boolean isEqual = str1.trim().equals(str2); // 返回 true
String str1 = "abc";
String str2 = "ABC";
boolean isEqual = str1.equalsIgnoreCase(str2); // 返回 true
EmployeeController类
@GetMapping("/export_employee_excel")
public void exportEmployeeExcel(HttpServletResponse response) {
try {
employeeService.exportEmployeeExcel(response);
} catch (IOException e) {
e.printStackTrace();
}
}
EmployeeService类:
public void exportEmployeeExcel(HttpServletResponse response) throws IOException {
List<Employee> kspwStudentSeatList = list();
try {
ExcelWriterBuilder workBook = EasyExcel.write(GlobalSet.download_url, Employee.class);
// sheet方法参数: 工作表的顺序号(从0开始)或者工作表的名字
workBook.sheet("员工信息").doWrite(kspwStudentSeatList);
downloadTempalate(response);
System.out.println("写入完成!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件
* @param response
* @throws IOException
*/
public static void downloadTempalate(HttpServletResponse response) throws IOException {
// 告诉浏览器用什么软件可以打开此文件
response.setHeader("content-Type", "application/vnd.ms-excel");
// 下载文件的默认名称
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("员工信息.xlsx", "utf-8"));
//4. 创建输入、输出流
FileInputStream input = new FileInputStream(GlobalSet.download_url);
ServletOutputStream sos = response.getOutputStream();
//IO流获取文件的字节流,然后再响应给浏览器
byte[] arr = new byte[1024];
int res = 0;
while((res = input.read(arr)) > 0){
//将读取的内容输出到输出流中
sos.write(arr, 0, res);
}
input.close();
sos.close();
}
你好!根据你提供的信息,我了解到你在使用easyExcel做模板校验时遇到了一个问题,即同样的字符串使用equals方法进行比较时返回false。这可能是因为字符串对象的比较需要使用equals方法进行内容比较,而不是使用"=="或者"!="进行引用比较。下面我将给出具体的解决方案来解决你的问题。
在Java中,字符串对象的比较需要使用equals方法,这是因为字符串是对象,对象的比较使用equals方法来判断对象的内容是否相等。在Java中,"=="和"!="操作符用于判断两个对象是否引用了同一个对象,而不是判断两个对象的内容是否相等。
解决方法如下:
String str1 = "Hello";
String str2 = "Hello";
boolean isEqual = str1.equals(str2);
System.out.println(isEqual); // 输出结果为true
这段代码会使用equals方法比较str1和str2的内容,由于它们的内容相同,所以isEqual的值为true。
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equalsIgnoreCase(str2);
System.out.println(isEqual); // 输出结果为true
这段代码会使用equalsIgnoreCase方法比较str1和str2的内容,由于它们的内容相同(忽略大小写),所以isEqual的值为true。
String str1 = " Hello ";
String str2 = "Hello";
boolean isEqual = str1.trim().equals(str2.trim());
System.out.println(isEqual); // 输出结果为true
这段代码会使用trim方法去除str1和str2的首尾空格,然后使用equals方法比较它们的内容,由于它们的内容相同,所以isEqual的值为true。
通过上述的方法,你可以正确地比较字符串对象的内容,而不会出现返回false的情况。希望这些解决方案能够帮助到你!如果你还有任何问题,请随时提问。