Home Java javaTutorial Java code example for converting excel to txt and vice versa

Java code example for converting excel to txt and vice versa

May 08, 2017 pm 03:46 PM

本篇文章主要介绍了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); 
  } 
 } 
}
Copy after login
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(); 
} 
} 
}
Copy after login

遇到的问题:

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);
Copy after login

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

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

【相关推荐】

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles