使用c#设置excel的缩放大小

时间:2018-03-13 09:49:02

标签: c# arrays excel

我想在下载之前将excel中的缩放大小设置为75%编程。默认情况下,默认值设置为100%。任何人都可以帮我解决这个问题吗?

我使用下面的代码从报告中获取数据并将其存储在字节数组中

 bytes = rptViewer.ServerReport.Render("EXCELOPENXML", deviceInfo,
                    out mimeType, out encoding, out extensions, out streamids, out warnings);

然后将信息传递给下面的方法以在excel中下载文件

private HttpResponseMessage DownloadFile(string mimeType, byte[] bytes, string rptName, string extensions)
    {
        string fileName = rptName + "." + extensions;
        HttpRequestMessage msg = new HttpRequestMessage();
        if (!string.IsNullOrEmpty(fileName))
        {
            HttpResponseMessage response = new HttpResponseMessage();
            response.Content = new ByteArrayContent(bytes);
            response.Content.Headers.Add("x-filename", fileName);
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(mimeType);
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = fileName;
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
        return msg.CreateResponse(HttpStatusCode.NotFound, "File not found.");
    }

因此,下载时默认设置为100%。我希望它默认为75%。

2 个答案:

答案 0 :(得分:0)

找到一种访问Excel.Application的方法。那就足够了:

Application.ActiveWindow.Zoom = 75

通常,此代码会打开工作簿并将每个工作表设置为10缩放。您可以将其用作参考:

using System;
using Excel = Microsoft.Office.Interop.Excel;

class LooperMain
{
    static void Main()
    {
        Excel.Application excel = new Excel.Application();
        excel.Visible = true;
        string strReportName = @"C:\somePath\123.xlsx";
        Excel.Workbook wkb =  Open(excel, strReportName);
        SetZoom(10, wkb, excel);
    }

    public static void SetZoom(int zoomLevel, 
                              Excel.Workbook wb, 
                              Excel.Application excelInstance)
    {
        foreach (Excel.Worksheet ws in wb.Worksheets)
        {
            ws.Activate();
            excelInstance.ActiveWindow.Zoom = zoomLevel;
        }
    }

    public static Excel.Workbook Open(Excel.Application excelInstance, 
                               string fileName, bool readOnly = false, 
                               bool editable = true, bool updateLinks = true)
    {
        Excel.Workbook book = excelInstance.Workbooks.Open(
            fileName, updateLinks, readOnly);                                  
        return book;
    }
}

答案 1 :(得分:0)

SSRS或报表查看器不提供自定义导出的Excel文件缩放级别的方法。 您可能需要将字节保存到文件中,使用excel操作库(如ClosedXML)以编程方式打开它,更改缩放级别并将文件写回响应。

File.WriteAllBytes("Foo.xlsx", bytes);
var wb = new XLWorkbook("Foo.xlsx");
var ws = wb.Worksheet(1);
ws.SheetView.ZoomScale = 70;
wb.SaveAs("Bar.xlsx");
bytes = File.ReadAllBytes("Bar.xlsx"); 
var stream = new MemoryStream(bytes);   
... //response creation
response.Content = new StreamContent(stream);  
...