C# 通过文件结构直接生成xls(Excel)文件

时间:2022-05-15 13:32:28

以下代码演示了 直接通过excel可以识别的文件结构生成xls文件的方法,这样就可以不引用麻烦的ole了。
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);
         }
     }
}