C# 通过excel可识别的xml结构直接生成xls文件

上一片文章演示了如何根据简单的excel文件结构直接生成xls文件,如果涉及到合并,公式之类的复杂操作,可以使用xml结构来直接构造xls文件,比如生成如下所示文件

using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
namespace ConsoleApplication17
{
    class Program
    {
        static void Main(string[] args)
        {
            
            ExcelWriter excel = new ExcelWriter();

            excel.CreateSheet("XmlData");//sheetName
            //增加一列,默认可以不加
            excel.CreateColumn(5, 100);
            //新增表头行
            excel.CreateRow();
            excel.CreateCellString("Name");
            excel.CreateCellString("Score1");
            excel.CreateCellString("Score1");
            excel.CreateCellString("Score0");
            excel.CreateCellString("说明");
            //新增两行数据
            excel.CreateRow();
            excel.CreateCellString("jinjazz");
            excel.CreateCellNumber(100);
            excel.CreateCellNumber(98);
            excel.CreateCell(0, "Number", "RC[-2]+RC[-1]",1,1); //公式,-2和-1代表当前cell的水平偏移量
            excel.CreateCell(0, "String", "RC[-4]&\":\"&RC[-1]", 1, 1);//公式
            excel.CreateRow();
            excel.CreateCellString("游客");
            excel.CreateCellNumber(33);
            excel.CreateCellNumber(14);
            excel.CreateCell(0, "Number", "RC[-2]+RC[-1]", 1, 1);
            excel.CreateCell(0, "String", "RC[-4]&\":\"&RC[-1]", 1, 1);
            //新增汇总行
            excel.CreateRow();
            excel.CreateCellString("总计");
            excel.CreateCell(0, "Number", "SUM(R[-2]C:R[-1]C)", 1, 1);//公式,-2和-1代表cell的垂直偏移量
            excel.CreateCell(0, "Number", "SUM(R[-2]C:R[-1]C)", 1, 1);
            excel.CreateCell(0, "Number", "SUM(R[-2]C:R[-1]C)", 1, 1);
            //增加三个空行
            excel.CreateRow();
            excel.CreateRow();
            excel.CreateRow();
            //增加一个合并过的单元格
            excel.CreateCell("http://blog.csdn.net/jinjazz","String",null,2,5);

            excel.Save(@"c:\testData.xls");
        }
    }
    public class ExcelWriter
    {
        string ssns = "urn:schemas-microsoft-com:office:spreadsheet";
        string xmlns = "urn:schemas-microsoft-com:office:spreadsheet";
        XmlDocument _doc = new XmlDocument();
        XmlNode _currentSheet = null;
        XmlNode _currentRow = null;
        
        public ExcelWriter()
        {
            //excel的xml模版,你需要了解xml的Attributes怎么用
            StringBuilder sbody = new StringBuilder();
            sbody.Append("<?xml version=\"1.0\"?>\n");
            sbody.Append("<?mso-application progid=\"Excel.Sheet\"?>\n");
            sbody.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n");
            sbody.Append("xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n");
            sbody.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n");
            sbody.Append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\n");
            sbody.Append("xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n");
            sbody.Append("<Styles>\n");
            sbody.Append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n");
            sbody.Append("<Alignment ss:Vertical=\"Center\"/>\n");
            sbody.Append("<Borders/>\n");
            sbody.Append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"10\"/>\n");
            sbody.Append("<Interior/>\n");
            sbody.Append("<NumberFormat/>\n");
            sbody.Append("<Protection/>\n");
            sbody.Append("</Style>\n");
            sbody.Append("</Styles>\n");
            sbody.Append("</Workbook>\n");
            _doc.LoadXml(sbody.ToString());
        }
        /// <summary>
        /// 增加一个工作表
        /// </summary>
        /// <param name="sheetName">工作表名称</param>
        public void CreateSheet(string sheetName)
        {
            System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Worksheet", ssns);
            System.Xml.XmlAttribute xa = _doc.CreateAttribute("ss", "Name", xmlns);
            xa.Value = sheetName;
            node.Attributes.Append(xa);
            _doc.ChildNodes[2].AppendChild(node);
            node.AppendChild(_doc.CreateNode(XmlNodeType.Element, "Table", xmlns));
            _currentSheet = node;
        }
        /// <summary>
        /// 增加一行
        /// </summary>
        public void CreateRow()
        {
            System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Row", xmlns);
            _currentSheet.ChildNodes[0].AppendChild(node);
            _currentRow = node;
        }
        /// <summary>
        /// 增加一列
        /// </summary>
        /// <param name="index">索引</param>
        /// <param name="width">宽度</param>
        public void CreateColumn(int index,float width)
        {
            System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Column", xmlns);
            System.Xml.XmlAttribute xa = _doc.CreateAttribute("ss", "Index", xmlns);
            xa.Value = index.ToString();
            node.Attributes.Append(xa);
            xa = _doc.CreateAttribute("ss", "Width", xmlns);
            xa.Value = width.ToString();
            node.Attributes.Append(xa);
            _currentSheet.ChildNodes[0].AppendChild(node);
        }
        /// <summary>
        /// 增加一个单元格
        /// </summary>
        /// <param name="value">值</param>
        /// <param name="Type">类型</param>
        /// <param name="Expression">公式</param>
        /// <param name="rowSpan">跨行</param>
        /// <param name="colSpan">跨列</param>
        public void CreateCell(object value, string Type, string Expression, int rowSpan, int colSpan)
        {
            System.Xml.XmlAttribute xa = null;
            System.Xml.XmlNode nodeCell = _doc.CreateNode(XmlNodeType.Element, "Cell", xmlns);
            _currentRow.AppendChild(nodeCell);
            if (!string.IsNullOrEmpty(Expression))
            {
                xa = _doc.CreateAttribute("ss", "Formula", xmlns);
                xa.Value = "=" + Expression;
                nodeCell.Attributes.Append(xa);
            }
            if (--colSpan > 0)
            {
                xa = _doc.CreateAttribute("ss", "MergeAcross", xmlns);
                xa.Value = colSpan.ToString();
                nodeCell.Attributes.Append(xa);
            }
            if (--rowSpan > 0)
            {
                xa = _doc.CreateAttribute("ss", "MergeDown", xmlns);
                xa.Value = rowSpan.ToString();
                nodeCell.Attributes.Append(xa);
            }
            System.Xml.XmlNode nodeData = _doc.CreateNode(XmlNodeType.Element, "Data", xmlns);
            xa = _doc.CreateAttribute("ss", "Type", xmlns);
            xa.Value = Type;
            nodeData.Attributes.Append(xa);
            nodeData.InnerText = value.ToString();
            nodeCell.AppendChild(nodeData);
        }
        /// <summary>
        /// 增加一个数字单元格
        /// </summary>
        /// <param name="value"></param>
        public void CreateCellNumber(double value)
        {
            CreateCell(value, "Number", null, 1, 1);
        }
        /// <summary>
        /// 增加一个字符串单元格
        /// </summary>
        /// <param name="value"></param>
        public void CreateCellString(string value)
        {
            CreateCell(value, "String", null, 1, 1);
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="strFile"></param>
        public void Save(string strFile)
        {
            _doc.Save(strFile);
        }

    }

    
}

上面代码基本都是对xml文件的操作,需要你对xml的dom对象比较熟悉,尤其是Attributes的使用。
通过增加xml的style相关节点可以设置单元格样式,这个留给大家来做吧。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值