导出Excel 并且适应列宽的长度

这段代码展示了如何使用C#导出数据到Excel文件,并通过`AutoFit`方法使列宽自动适应内容长度。数据源被处理为`DataObject[]`数组,逐行写入Excel工作表,最后保存并关闭工作簿。此外,还包含了一个获取Web应用根路径的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    ///DataObject[] 可以把它试做为DataTable

private void ExportExcel(DataObject[] objs)
    {
        //读取Excel路徑
        string excelSource = Server.MapPath("SIP016Export.xls");
        string FileName = "SIP016Export.xls";
        string tempFolder = "../../../tempFolder/";
        string tempFilePath = Server.MapPath(tempFolder + FileName);
        File.Copy(excelSource, tempFilePath, true);
        object missing = System.Type.Missing;
        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        Workbook workbook = app.Workbooks._Open(tempFilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
        Worksheet worksheet = (Worksheet)workbook.Worksheets[1];
        app.Visible = false;

        for (int i = 0; i < objs.Length; i++)
        {
            worksheet.Cells[i + 2, 1] = objs[i].getData("SUNITATRR_CV");
            worksheet.Cells[i + 2, 2] = objs[i].getData("SORG_CV");
            worksheet.Cells[i + 2, 3] = objs[i].getData("SSUBJECT_CV");
            worksheet.Cells[i + 2, 4] = objs[i].getData("SMSUBJECT_CV");
        }
        worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
        workbook.Save();
        app.Quit();
        string path = GetRootURI() + "/tempFolder/SIP016Export.xls?date=" + DateTime.Now.ToString();
        Response.Write("window.open('" + path + "','download','height=50,width=50,top=0,left=0');");
    }

 

    /// <summary>
    /// 獲取平臺web物理路徑
    /// </summary>
    /// <returns></returns>
    public string GetRootURI()
    {
        string AppPath = "";
        HttpContext HttpCurrent = HttpContext.Current;
        HttpRequest Req;
        if (HttpCurrent != null)
        {
            Req = HttpCurrent.Request;
            string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
            if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
            {
                AppPath = UrlAuthority;
            }
            else
            {
                AppPath = UrlAuthority + Req.ApplicationPath;
            }
        }
        return AppPath;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值