2014年11月24日 星期一

[ClosedXML] 使用語法紀錄

using ClosedXML.Excel;

var workbook = new XLWorkbook(templateFilePath);
var worksheet = workbook.Worksheets.Worksheet(1);

//set cell value
worksheet.Cell(Row, Col).Value = string;

//set value by using DataTable
for (int j = 0; j < Data.Rows.Count; j++)
{
    for (int k = 0; k < Data.Columns.Count; k++)
    {
          worksheet.Cell(j, k).Value = Data.Rows[j][k].ToString();
     }
}

//set cell value in center
worksheet.Cell(R, C).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
worksheet.Cell(R, C).Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;

//set border line
worksheet.Cell(R, C).Style.Border.SetRightBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetTopBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetBottomBorder(XLBorderStyleValues.Thin);
worksheet.Cell(R, C).Style.Border.SetLeftBorder(XLBorderStyleValues.Thin);

//column fit
worksheet.Column(columnIndex).AdjustToContents();
worksheet.Column(columnIndex).Width -= 1;

//merging columns
//Merge(true) might cause files error?
worksheet.Range(R, C, R2, C2).Column(1).Merge();

//copying worksheets
worksheet.CopyTo(sheetName);
worksheet.CopyTo(workbook2, sheetName);


workbook.SaveAs(filePath);


參考資料:
http://closedxml.codeplex.com/documentation
https://closedxml.codeplex.com/wikipage?title=Copying%20Worksheets
https://closedxml.codeplex.com/wikipage?title=Merging%20Cells

沒有留言:

張貼留言