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

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


演示代码如下,调用相当简单。
C# code
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";