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;
}

 

 

 

posted @ 2021-05-05 10:28  码农阿亮  阅读(99)  评论(0编辑  收藏  举报