日期:2014-05-20  浏览次数:20804 次

[攒分贴] 通过文件结构直接生成xls文件
直接通过excel可以识别的文件结构生成xls文件的方法,这样就可以不引用麻烦的ole了

C# code
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication16
{
    class Program
    {
        static void Main(string[] args)
        {
            //不通过OLE生成excel文件的方法
            ExcelWriter excel = new ExcelWriter(@"c:\test.xls");
            excel.BeginWrite();
            excel.WriteString(0, 0, "Name");
            excel.WriteString(0, 1, "Score");
            excel.WriteString(1, 0, "jinjazz"); 
            excel.WriteNumber(1, 1, 100);
            excel.WriteString(2, 0, "游客");
            excel.WriteNumber(2, 1, 0);
            excel.EndWrite();
        }
    }
    public class ExcelWriter
    {
        System.IO.FileStream _wirter;
        public ExcelWriter(string strPath)
        {
            _wirter = new System.IO.FileStream(strPath, System.IO.FileMode.OpenOrCreate);
        }
        /// <summary>
        /// 写入short数组
        /// </summary>
        /// <param name="values"></param>
        private void _writeFile(short[] values)
        {
            foreach (short v in values)
            {
                byte[] b = System.BitConverter.GetBytes(v);
                _wirter.Write(b, 0, b.Length);
            }
        }
        /// <summary>
        /// 写文件头
        /// </summary>
        public void BeginWrite()
        {
            _writeFile(new short[] { 0x809, 8, 0, 0x10, 0, 0 });
        }
        /// <summary>
        /// 写文件尾
        /// </summary>
        public void EndWrite()
        {
            _writeFile(new short[] { 0xa, 0 });
            _wirter.Close();
        }
        /// <summary>
        /// 写一个数字到单元格x,y
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="value"></param>
        public void WriteNumber(short x, short y, double value)
        {
            _writeFile(new short[] { 0x203, 14, x, y, 0 });
            byte[] b = System.BitConverter.GetBytes(value);
            _wirter.Write(b, 0, b.Length);
        }
        /// <summary>
        /// 写一个字符到单元格x,y
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <param name="value"></param>
        public void WriteString(short x, short y, string value)
        {
            byte[] b = System.Text.Encoding.Default.GetBytes(value);
            _writeFile(new short[] { 0x204, (short)(b.Length + 8), x, y,0, (short)b.Length });
            _wirter.Write(b, 0, b.Length);
        }
    }
}



blog同步更新:
http://blog.csdn.net/jinjazz/archive/2008/08/01/2753869.aspx

------解决方案--------------------
......牛x
对这都有研究