首先要感谢jinjazz,没有他的《通过文件结构直接生成xls文件》(http://blog.csdn.net/jinjazz/archive/2008/08/01/2753869.aspx)是不会有这份Java版代码的。
- import java.io.*;
- public class MakeExcel {
- public MakeExcel() {
- }
- public static void main(String[] args) {
- File file = null;
- FileOutputStream fos = null;
- try {
- file = new File("test.xls");
- file.createNewFile();
- fos = new FileOutputStream(file);
- writeBegin(fos);
- writeNumber(fos, (short) 4, (short) 4, 40.5);
- writeString(fos, (short) 10, (short) 10, "中文测试");
- writeEnd(fos);
- fos.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- static void writeBegin(FileOutputStream fos) {
- try {
- short[] header = new short[] {0x809, 8, 0, 0x10, 0, 0};
- for (byte i = 0; i < header.length; i++) {
- fos.write(short2bytes(header[i]));
- }
- } catch (Exception e) {}
- }
- static void writeEnd(FileOutputStream fos) {
- try {
- short[] end = new short[] {0xa, 0};
- for (byte i = 0; i < end.length; i++) {
- fos.write(short2bytes(end[i]));
- }
- } catch (Exception e) {}
- }
- static void writeString(FileOutputStream fos, short x, short y,
- String s) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(baos);
- dos.write((new String(s.getBytes("utf-8"), "utf-8")).getBytes());
- dos.close();
- baos.close();
- byte[] b = baos.toByteArray();
- short[] a = new short[] {0x204, (short) (b.length + 8), x, y, 0,
- (short) b.length};
- for (byte i = 0; i < a.length; i++) {
- fos.write(short2bytes(a[i]));
- }
- fos.write(b);
- } catch (Exception e) {}
- }
- static void writeNumber(FileOutputStream fos, short x, short y,
- double number) {
- try {
- short[] a = new short[] {0x203, 14, x, y, 0};
- for (byte i = 0; i < a.length; i++) {
- fos.write(short2bytes(a[i]));
- }
- fos.write(double2bytes(number));
- } catch (Exception e) {}
- }
- static byte[] double2bytes(double x) {
- try {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(baos);
- dos.writeDouble(x);
- dos.close();
- baos.close();
- byte[] r = baos.toByteArray();
- for (int i = 0; i < r.length / 2; i++) {
- byte tmp = r[i];
- r[i] = r[r.length - 1 - i];
- r[r.length - 1 - i] = tmp;
- }
- return r;
- } catch (Exception e) {
- return null;
- }
- }
- static byte[] int2bytes(int x) {
- byte[] b = new byte[4];
- for (int i = 0; i < b.length; i++) {
- b[i] = (byte) x;
- x >>= 8;
- }
- return b;
- }
- static byte[] short2bytes(int x) {
- byte[] b = new byte[2];
- for (int i = 0; i < b.length; i++) {
- b[i] = (byte) x;
- x >>= 8;
- }
- return b;
- }
- }