search
HomeJavajavaTutorialJava code example for converting excel to txt and vice versa

本篇文章主要介绍了java实现excel和txt文件互转的相关知识。具有很好的参考价值。下面跟着小编一起来看下吧

话不多说,请看代码:

import java.io.*; 
import jxl.*; 
import jxl.write.*; 

//用java将txt数据导入excel
public class CreateXLS 
{ 
public static void main(String args[]) 
{ 
 try 
 { 
   //打开文件 
   WritableWorkbook book= Workbook.createWorkbook(new File("测试.xls")); 
   //生成名为“第一页”的工作表,参数0表示这是第一页 
   WritableSheet sheet=book.createSheet("第一页",0); 
   //在Label对象的构造子中指名单元格位置是第一列第一行(0,0) 
   //以及单元格内容为test 
   Label label=new Label(0,0,"test"); 
   //将定义好的单元格添加到工作表中 
   sheet.addCell(label); 
   /*生成一个保存数字的单元格 
    必须使用Number的完整包路径,否则有语法歧义 
    单元格位置是第二列,第一行,值为789.123*/ 
   jxl.write.Number number = new jxl.write.Number(1,0,789.123); 
   sheet.addCell(number); 
   //写入数据并关闭文件 
   book.write(); 
   book.close(); 
  }catch(Exception e) 
  { 
   System.out.println(e); 
  } 
 } 
}
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

//用java将excel数据导入txt

public class WriteTxt {

public static void main(String[] args) { 
// TODO Auto-generated method stub 
String filepath = "d:\\demo.xls"; 

try { 
Workbook workbook = Workbook.getWorkbook(new File(filepath)); 
Sheet sheet = workbook.getSheet(0); 
File file = new File("d:/1.txt");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
// j为行数,getCell("列号","行号") 
int j = sheet.getRows();
int y = sheet.getColumns();
for (int i = 0; i < j; i++) { 
for(int x=0; x<y; x++){
Cell c = sheet.getCell(x, i); 
String s = c.getContents(); 
bw.write(s);
bw.write(" ");
bw.flush();
}
bw.newLine();
bw.flush();
} 
System.out.println("写入结束");
} catch (BiffException e) { 
e.printStackTrace(); 
} catch (IOException e) { 
e.printStackTrace(); 
} 
} 
}

遇到的问题:

txt文件中单元格数据之间用|分割,用string.split("\\|");提取数据      

用的jar包对excel2007不支持 从而导致转换出的是空文件

excel文件转txt文件时,用tab键分隔 分隔字符串数组时用String.split("\\  ",-1);

上线遇到的问题:

1.在windows上获取路径地址是以\分隔的,而在linux上获取的路径是以/分隔的,这要注意

2.默认情况下,Excel中每个单元格所能显示的数字为11位,输入超过11位的数值,系统自动将其转换为科学记数格式,当txt转excel时,有两种方法可以解决这个问题,第一种是在单元格数字前加个单引号,第二种是设置单元格的格式为文本格式,在上述代码中加入以下代码

WritableFont wf = new WritableFont(WritableFont.TIMES,12,WritableFont.NO_BOLD,false);
WritableCellFormat wcfF = new WritableCellFormat(NumberFormats.TEXT);
wcfF.setFont(wf);
CellView cv = new CellView();
cv.setFormat(wcfF);
cv.setSize(10*265);
sheet.setColumnView(j, cv);
Label label = new Label(j,n,s1[j]);
sheet.addCell(label);

3. 当txt转excel在windows上转换成功时,到linux服务器上转出的excel中汉字变成了乱码,因为FileWriter fw = new FileWriter(file);这句代码采用默认字符集解析,经过尝试,使用GBK解析文件,用以下代码可不出现乱码,

BufferedReader bw = new BufferedReader(new InputStreamReader(new FileInputStream(new File(filen)),"GBK"));

【相关推荐】

1. Java免费视频教程

2. 全面解析Java注解

3. 阿里巴巴Java开发手册

The above is the detailed content of Java code example for converting excel to txt and vice versa. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools