Java怎么将字符串集合导入EXCEL
时间: 2024-03-12 22:44:06 浏览: 142
java代码实现excel导入
5星 · 资源好评率100%
可以使用Apache POI库来将字符串集合导入Excel中。具体的步骤如下:
1. 创建一个工作簿对象:Workbook workbook = new XSSFWorkbook();
2. 创建一个工作表对象:Sheet sheet = workbook.createSheet("Sheet1");
3. 创建一个行对象,并设置表头:Row header = sheet.createRow(0); Cell headerCell = header.createCell(0); headerCell.setCellValue("字符串集合");
4. 遍历字符串集合,创建行并设置单元格值:int rowIndex = 1; for (String str : stringList) { Row row = sheet.createRow(rowIndex++); Cell cell = row.createCell(0); cell.setCellValue(str); }
5. 将工作簿写入到文件中:FileOutputStream outputStream = new FileOutputStream("data.xlsx"); workbook.write(outputStream);
完整的代码示例:
```
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class StringListToExcel {
public static void main(String[] args) throws Exception {
List<String> stringList = Arrays.asList("Java", "Python", "C++", "Ruby", "JavaScript");
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row header = sheet.createRow(0);
Cell headerCell = header.createCell(0);
headerCell.setCellValue("字符串集合");
int rowIndex = 1;
for (String str : stringList) {
Row row = sheet.createRow(rowIndex++);
Cell cell = row.createCell(0);
cell.setCellValue(str);
}
FileOutputStream outputStream = new FileOutputStream("data.xlsx");
workbook.write(outputStream);
workbook.close();
}
}
```
阅读全文