You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
102 lines
3.2 KiB
102 lines
3.2 KiB
import java.io.*;
|
|
import java.time.LocalDate;
|
|
import java.time.format.DateTimeFormatter;
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Locale;
|
|
|
|
public class ExcelReader {
|
|
|
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);
|
|
|
|
public static List<PostInfo> readExcelData(String filePath, int maxRows) {
|
|
List<PostInfo> posts = new ArrayList<>();
|
|
|
|
try (BufferedReader reader = new BufferedReader(new FileReader(filePath, java.nio.charset.StandardCharsets.UTF_8))) {
|
|
|
|
String line;
|
|
boolean isFirstLine = true;
|
|
int rowCount = 0;
|
|
|
|
while ((line = reader.readLine()) != null && rowCount < maxRows) {
|
|
if (isFirstLine) {
|
|
isFirstLine = false;
|
|
continue;
|
|
}
|
|
|
|
String[] parts = parseCSVLine(line);
|
|
if (parts.length >= 9) {
|
|
PostInfo post = parsePostInfo(parts);
|
|
if (post != null) {
|
|
posts.add(post);
|
|
rowCount++;
|
|
}
|
|
}
|
|
}
|
|
|
|
System.out.println("成功读取 " + posts.size() + " 条数据");
|
|
|
|
} catch (IOException e) {
|
|
System.err.println("读取文件时出错: " + e.getMessage());
|
|
}
|
|
|
|
return posts;
|
|
}
|
|
|
|
private static String[] parseCSVLine(String line) {
|
|
List<String> fields = new ArrayList<>();
|
|
StringBuilder currentField = new StringBuilder();
|
|
boolean inQuotes = false;
|
|
|
|
for (char c : line.toCharArray()) {
|
|
if (c == '"') {
|
|
inQuotes = !inQuotes;
|
|
} else if (c == ',' && !inQuotes) {
|
|
fields.add(currentField.toString().trim());
|
|
currentField.setLength(0);
|
|
} else {
|
|
currentField.append(c);
|
|
}
|
|
}
|
|
|
|
fields.add(currentField.toString().trim());
|
|
return fields.toArray(new String[0]);
|
|
}
|
|
|
|
private static PostInfo parsePostInfo(String[] parts) {
|
|
try {
|
|
PostInfo post = new PostInfo();
|
|
|
|
post.setTitle(parts[0]);
|
|
post.setContent(parts[1]);
|
|
post.setAuthor(parts[2]);
|
|
|
|
if (!parts[3].isEmpty()) {
|
|
post.setPostDate(LocalDate.parse(parts[3], DATE_FORMATTER));
|
|
}
|
|
|
|
post.setLikeCount(parseInt(parts[4]));
|
|
post.setCommentCount(parseInt(parts[5]));
|
|
post.setViewCount(parseInt(parts[6]));
|
|
|
|
post.setTags(parts[7]);
|
|
post.setSentiment(parts[8]);
|
|
|
|
return post;
|
|
} catch (Exception e) {
|
|
System.err.println("解析数据时出错: " + e.getMessage());
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private static int parseInt(String value) {
|
|
try {
|
|
if (value == null || value.isEmpty()) {
|
|
return 0;
|
|
}
|
|
return Integer.parseInt(value);
|
|
} catch (NumberFormatException e) {
|
|
return 0;
|
|
}
|
|
}
|
|
}
|
|
|