在记事本中,存放了两列数据:需要更改的数据和更改后的数据
,如下:
-----------------------------------------
需要更改的数据 更改后的数据
16 111
23 213
35 311
48 416
-----------------------------------------
现在要根据记事本中的数据,只在excel中的某列(如B列)进行查找,
如果找到了“需要更改的数据”,就将该数据替换成“更改后的数据”。
如:在B列中找到了16,就将16改成111
更改前的数据在哪?
更改后的数据在哪?
参考下 很简单的
-----------------------------------------
需要更改的数据 更改后的数据
16 111
23 213
35 311
48 416
-----------------------------------------
记录在记事本里面,
需要查找更改是数据记录在excel中
给你一个程序片段的地址
待修改的文本文件data.txt内容是这样的形式,不要有第一行
16 111
23 213
35 311
48 416
然后对应的Excel用的2007及以上格式,文件名为data.xlsx,待修改为第一列import java.io.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;/**
* 这个可以连接Excel2007和2010文件
* 作为学习POI的XSSF的入门实例
* @author GaoYong
*
*/
public class Data { /**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
//利用HashMap保存待修改数值的对应数值
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
BufferedReader br=new BufferedReader(new InputStreamReader(
new FileInputStream("resources/excel/data.txt")
));
String s=null;
while((s=br.readLine())!=null){
String[] nums=s.split(" ");
System.out.println("num[0]="+nums[0]+",num[1]="+nums[1]);
int[] n=new int[2];
n[0]=Integer.parseInt(nums[0]); //待更改数据
n[1]=Integer.parseInt(nums[1]); //对应更改为的数据
System.out.println("num[0]="+n[0]+",num[1]="+n[1]);
map.put(n[0],n[1]);//自动装箱的机制
} String filepath = "resources/excel/data.xlsx";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}// POIFSFileSystem pfs = null; XSSFWorkbook wb=null;
// HSSFWorkbook wb = null; try {
wb = new XSSFWorkbook(fis); } catch (IOException e3) {
e3.printStackTrace();
}
try{
fis.close();
}catch(Exception e){
e.printStackTrace();
} XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row = null;
XSSFCell cell = null; int a1 ;
int a2 = 0;
int rowNum; rowNum = sheet.getLastRowNum();
// sheet.getRow(0);//假如我们更改第一列 //假设我们对所有列更改
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
cell = row.getCell(0); //这里对第一列进行值的比对调整
a1=(int)cell.getNumericCellValue();
Set<Integer> set=map.keySet();
for(Integer num:set){
if(num.intValue()==a1){
//map获取到待修改的值,修改对应的单元格的值
cell.setCellValue(map.get(num));
System.out.println("修改从"+a1+"到"+map.get(num));
break;
}
}// cell = row.getCell(1);
// a2 = (int) cell.getNumericCellValue(); System.out.println(a1+"\t"); }
OutputStream os=new FileOutputStream("resources/excel/data.xlsx") ;
wb.write(os);
try {
os.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}}