DataTable 转 XLSX

DataTable 转 XLSX

 

public string DataTableToXlsx(DataTable vContent, string vOutputFilePath)
{
    string result;
    try
    {
        SLDocument sldocument = new SLDocument();
        if (File.Exists(vOutputFilePath))
        {
            File.Delete(vOutputFilePath);
        }
        sldocument.ImportDataTable(1, 1, vContent, true);
        for (int i = 0; i < vContent.Columns.Count; i++)
        {
            SLStyle slstyle = sldocument.CreateStyle();
            if (vContent.Columns[i].DataType.FullName.Equals("System.String"))
            {
                slstyle.FormatCode = "@";
            }
            else if (vContent.Columns[i].DataType.FullName.Equals("System.DateTime"))
            {
                slstyle.FormatCode = "yyyy/mm/dd hh:mm:ss";
            }
            else if (vContent.Columns[i].DataType.FullName.Equals("System.Int16"))
            {
                slstyle.FormatCode = "#";
            }
            else if (vContent.Columns[i].DataType.FullName.Equals("System.Int32"))
            {
                slstyle.FormatCode = "#";
            }
            else if (vContent.Columns[i].DataType.FullName.Equals("System.Int64"))
            {
                slstyle.FormatCode = "#";
            }
            else
            {
                slstyle.FormatCode = "General";
            }
            sldocument.SetColumnStyle(i + 1, slstyle);
            sldocument.AutoFitColumn(i + 1, vContent.Columns.Count, 300.0);
        }
        SLTable sltable = sldocument.CreateTable(1, 1, vContent.Rows.Count + 1, vContent.Columns.Count);
        sltable.SetTableStyle(SLTableStyleTypeValues.Medium1);
        sldocument.InsertTable(sltable);
        sldocument.SaveAs(vOutputFilePath);
        result = "OK";
    }
    catch (Exception ex)
    {
        throw new Exception("DataTable to Xlsx : \n" + ex.Message);
    }
    return result;
}

 

 

 

上一篇:详解DataTable DataSet以及与数据库的关系


下一篇:UFT 关于excel及datatable的处理