寫入資料前都要先建立一個Cell物件 :
public static Cell CreateStringCell(string col, uint row, string txt)
{
Cell cell = new Cell() { CellReference = col + row };
cell.DataType = new EnumValue<CellValues>(CellValues.String);
cell.CellValue = new CellValue();
cell.CellValue.Text = txt;
{
Cell cell = new Cell() { CellReference = col + row };
cell.DataType = new EnumValue<CellValues>(CellValues.String);
cell.CellValue = new CellValue();
cell.CellValue.Text = txt;
return cell;
}
}
然后在一個row中: row.InsertAt(cell, 0); Cell物件有很多屬性, 如StyleIndex, CellFormula. 如何加入style?
style就是控制字型, 顏色等, 是一個物件: Stylesheet stylesheet = new Stylesheet();
設定字型:
stylesheet.Fonts = new Fonts();
stylesheet.Fonts.Count = 2; //indes由0開始, 必須有一個, 0, 1 等于2個
stylesheet.Fonts.Count = 2; //indes由0開始, 必須有一個, 0, 1 等于2個
先建立字型物件:
Font f1 = new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize() { Val = 9D },
new Color() { Rgb = "FF000000" },
new FontName() { Val = "Calibri" },
new DocumentFormat.OpenXml.Spreadsheet.FontScheme() { Val = FontSchemeValues.Minor }
); // Id = 0
new Color() { Rgb = "FF000000" },
new FontName() { Val = "Calibri" },
new DocumentFormat.OpenXml.Spreadsheet.FontScheme() { Val = FontSchemeValues.Minor }
); // Id = 0
加入字型:
stylesheet.Fonts.Append(f1);
然后到設定cell format :
stylesheet.CellFormats = new CellFormats();
stylesheet.CellFormats.Count = 3;
stylesheet.CellFormats.Count = 3;
CellFormat default_cf = new CellFormat() { FontId = 0, NumberFormatId = 0, BorderId = 0, FillId = 0 };
default_cf.Alignment = new Alignment();
default_cf.Alignment.Horizontal = HorizontalAlignmentValues.Left;
default_cf.ApplyAlignment = true;
default_cf.Alignment = new Alignment();
default_cf.Alignment.Horizontal = HorizontalAlignmentValues.Left;
default_cf.ApplyAlignment = true;
一個CellFormats就包含4個物件: FontId, NumberFormatId , BorderId , FillId , 全部引用id. 最后 stylesheet.CellFormats.Append(default_cf); 記住CellFormat物件的id, 第一個為預設(index等于0), 由第2個始計(index等于1). 創建cell時候, 就要指定 cell.StyleIndex = styleIndex;
SDK有太多內容可以去深究, 留待大家慢慢究, 然后一齊分享:P 下面補充下 XML Spreadsheet 使用法.
因為HTML為XML一個子集, 所以html中的table可以被excel2003解讀到, 即使不是標準office xml都無問題. 不過excel有資料類型的區分, 同一個column會出現數字, 字串的混合情況, 可解釋為數字的就變成數字, 但很多時候我地都想全部資料以字串出現. 如何在<td></td> 中加入資料型別? 只要加上x:str 或 x:num, 或 mso-number-format: XXXX; 就 OK.
先在<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" >加返office namespace, 就可以使用.
(完)
發表留言