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

来源:互联网 发布:中国象棋对弈软件 编辑:程序博客网 时间:2024/05/16 12:22

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

 

原创粉丝点击