通过文件结构直接生成xls文件

本文介绍了一种使用C#直接生成Excel文件的方法,避免了使用OLE组件的复杂性。通过示例代码展示了如何创建.xls文件,包括写入字符串和数字等基本操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下代码演示了 直接通过excel可以识别的文件结构生成xls文件的方法,这样就可以不引用麻烦的ole了。

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ConsoleApplication16
  5. {
  6. class Program
  7. {
  8. static void Main( string []args)
  9. {
  10. //不通过OLE生成excel文件的方法
  11. ExcelWriterexcel= new ExcelWriter(@ "c:\test.xls" );
  12. excel.BeginWrite();
  13. excel.WriteString(0,0, "Name" );
  14. excel.WriteString(0,1, "Score" );
  15. excel.WriteString(1,0, "jinjazz" );
  16. excel.WriteNumber(1,1,100);
  17. excel.WriteString(2,0, "游客" );
  18. excel.WriteNumber(2,1,0);
  19. excel.EndWrite();
  20. }
  21. }
  22. public class ExcelWriter
  23. {
  24. System.IO.FileStream_wirter;
  25. public ExcelWriter( string strPath)
  26. {
  27. _wirter= new System.IO.FileStream(strPath,System.IO.FileMode.OpenOrCreate);
  28. }
  29. ///<summary>
  30. ///写入short数组
  31. ///</summary>
  32. ///<paramname="values"></param>
  33. private void _writeFile( short []values)
  34. {
  35. foreach ( short v in values)
  36. {
  37. byte []b=System.BitConverter.GetBytes(v);
  38. _wirter.Write(b,0,b.Length);
  39. }
  40. }
  41. ///<summary>
  42. ///写文件头
  43. ///</summary>
  44. public void BeginWrite()
  45. {
  46. _writeFile( new short []{0x809,8,0,0x10,0,0});
  47. }
  48. ///<summary>
  49. ///写文件尾
  50. ///</summary>
  51. public void EndWrite()
  52. {
  53. _writeFile( new short []{0xa,0});
  54. _wirter.Close();
  55. }
  56. ///<summary>
  57. ///写一个数字到单元格x,y
  58. ///</summary>
  59. ///<paramname="x"></param>
  60. ///<paramname="y"></param>
  61. ///<paramname="value"></param>
  62. public void WriteNumber( short x, short y, double value)
  63. {
  64. _writeFile( new short []{0x203,14,x,y,0});
  65. byte []b=System.BitConverter.GetBytes(value);
  66. _wirter.Write(b,0,b.Length);
  67. }
  68. ///<summary>
  69. ///写一个字符到单元格x,y
  70. ///</summary>
  71. ///<paramname="x"></param>
  72. ///<paramname="y"></param>
  73. ///<paramname="value"></param>
  74. public void WriteString( short x, short y, string value)
  75. {
  76. byte []b=System.Text.Encoding.Default.GetBytes(value);
  77. _writeFile( new short []{0x204,( short )(b.Length+8),x,y,0,( short )b.Length});
  78. _wirter.Write(b,0,b.Length);
  79. }
  80. }
  81. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值