java - 如何使用 JAVA POI 写入列的数据以从输入 excel 输出 excel
问题描述
我的要求是从输入 excel 文件中读取数据并将其写入输出 excel 文件我正在使用 JAVA 8 和 APACHE POI
在写入过程中,我将特定列的日期格式从mm/dd/yyyy更改为dd/mm/yyyy
使用下面的代码在 excel 中设置当前日期,我想在输出 excel 中设置相同的输入 excel 值,但定义了新格式。
任何帮助将非常感激
以下是更新的代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFCreationHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class DateFormatDemo1{
public static void main( String[] args ) throws IOException, InvalidFormatException, ParseException
{
OPCPackage pkg = OPCPackage.open(new File("C:\\DateFormatIssue\\SourceFile\\S.xlsx"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
XSSFCreationHelper createHelper = wb.getCreationHelper();
XSSFSheet sheet = wb.getSheetAt(0); // Create spreadsheet in workbook
Iterator<Row> iterator = sheet.iterator();
Cell cell = null;
Row row=null;
row=iterator.next();
int pos=11;
while(iterator.hasNext())
{
row=iterator.next();
cell= row.getCell(pos-1);
XSSFCellStyle cellStyle = (XSSFCellStyle)cell.getCellStyle();
cellStyle.setDataFormat( createHelper.createDataFormat().getFormat("M/dd/yyyy")); // set the format of the date
SimpleDateFormat sdf = new SimpleDateFormat("d/M/yyyy");
Date d=null;
/** below if block converts dates which are in format d/M/yyyy (15/04/2017) to M/d/yyyy (4/15/2017)**/
if (cell.getCellType() == Cell.CELL_TYPE_STRING)
{
d= sdf.parse(cell.getStringCellValue());
cell.setCellValue(d);
cell.setCellStyle(cellStyle);
}
else if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
cell.setCellValue(cell.getNumericCellValue());
}
}
FileOutputStream outFile =new FileOutputStream(new File("C:\\DateFormatIssue\\OutputFile\\output.xlsx"));
wb.write(outFile);
wb.close();
outFile.close();
pkg.close();
}}
解决方案
推荐阅读
- sorting - 如何使用类似地图的闭包对 Rust 向量进行排序?
- android - MVVM - 在片段中,我为什么要将 Viewmodel 观察者放在 onCreate 中?
- arrays - MongoDB / Mongoose - 更新元素较少的数组字段时出现问题
- python - 如何创建 1 对 1 的前馈层?
- python-3.x - 无法将参数从“.bat”文件传递给 python 脚本
- python - 不存在循环依赖时如何解决导入错误
- android - 如何在我的 Android 应用程序运行时限制用户连接 USB?
- python - 在 loglog 图中更改刻度标签
- elisp - 导出为 HTML 时将 org-id 嵌入到它们的标题中
- apache-spark - Spark Structured Streaming:处理负载是否会影响输入速率/numInputRecords?