两种OpenXML创建Excel单元格的方式比较

先给两种使用OpenXML创建Excel单元格的代码

第一种:

private Cell CreateTextCell(int columnIndex, int rowIndex, object cellValue, Nullable<uint> styleIndex)
{
     Cell cell = new Cell();//创建单元格

     cell.DataType = CellValues.InlineString;//设置单元格的数据类型

     cell.CellReference = GetCellReference(columnIndex) + rowIndex;
	//设置单元格的坐标,如A1

     if (styleIndex.HasValue)
          cell.StyleIndex = styleIndex.Value;
	//存在单元格格式则应用改格式

     InlineString inlineString = new InlineString();

     Text txt = new Text();
     txt.Text = cellValue.ToString(); 
     inlineString.AppendChild(txt);

     cell.AppendChild(inlineString);//设置单元格显示的值

     return cell;
}

第二种:

private Cell CreateValueCell(int columnIndex, int rowIndex, object cellValue, Nullable<uint> styleIndex)
{
    Cell cell = new Cell();
    cell.CellReference = GetCellReference(columnIndex) + rowIndex;

     //有格式则应用格式
     if (styleIndex.HasValue)
           cell.StyleIndex = styleIndex.Value;

    //使用CellValue对象设置单元格的值
    CellValue value = new CellValue(); 
    value.Text = cellValue.ToString();
   //赋值,仅这一步还不行,还得要下面一步

     cell.AppendChild(value); //将值应用的到单元格

     return cell;
} 

补充上述GetCellReference(columnIndex)代码如下:

private string GetCellReference(int colIndex)
{
     int dividend = colIndex;
     string columnName = String.Empty;
     int modifier;

     while (dividend > 0)
     {
         modifier = (dividend - 1) % 26;
         columnName = Convert.ToChar(65 + modifier).ToString() + columnName;
         dividend = (int)((dividend - modifier) / 26);
     }

     return columnName;
}

一般在表格中,数字右对齐,文本左对齐。但使用第一种创建单元格方式就不会有这种效果。

两种效果图比较:

第一种:

image

第二种:

image

 

可以看出在使用第一种打开Excel会出现一黄色感叹号,点开会提示您应用格式。第二种创建方式会根据传入的数据类型自行决定对齐方式。

转载于:https://www.cnblogs.com/pszw/archive/2011/11/20/OpenXML_CellValue.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值