问题
I need help with changing excel 2007 document orientation to landscape. I have not found any helpful information about this. I am using OpenXML SDK for this. The only thing I have found: when I create a new Worksheet I should set PageSetup() { Orientation = OrientationValue.Landscape}; But this doesn't help. Can anybody help with this problem? Thank you.
回答1:
You're on the right track with the OrientationValue.Landscape. You just need to loop through all worksheets and set the orientation attribute on the PageSetup element in order to set all worksheets to landscape:
public static void SetLandscape(SpreadsheetDocument document)
{
WorkbookPart workbookPart = document.WorkbookPart;
IEnumerable<string> worksheetIds = workbookPart.Workbook.Descendants<Sheet>().Select(w => w.Id.Value);
WorksheetPart worksheetPart;
foreach (string worksheetId in worksheetIds)
{
worksheetPart = ((WorksheetPart)workbookPart.GetPartById(worksheetId));
PageSetup pageSetup = worksheetPart.Worksheet.Descendants<PageSetup>().FirstOrDefault();
if (pageSetup != null)
{
pageSetup.Orientation = OrientationValues.Landscape;
}
worksheetPart.Worksheet.Save();
}
workbookPart.Workbook.Save();
}
The pattern I use to manipulate documents is to first open excel and create a blank document and save it. I then use my code to open that document and doing any work I need to it. This way I don't have to be bothered with creating a the elements and making sure things are in the right place. The code I use to achieve this is here:
public byte[] Export(string pathToExcelFile)
{
// Open the file from the drive
byte[] byteArray = File.ReadAllBytes(pathToExcelFile)
using (MemoryStream stream = new MemoryStream())
{
stream.Write(byteArray, 0, (int)byteArray.Length);
using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true))
{
// Do all work on excel doc here
SetLandscape(spreadsheetDoc);
// Save all the changes
}
return stream.ToArray();
}
}
So here I open the file from the drive into a memory stream so I can perform all the edits in memory. I then pass that document in the SetLandscape method and it will set the landscape property on all three sheets (3 sheets since that is the default for a blank excel 2007 document). I then save my changes and return the stream as a byte array. I do this so the file can be downloaded. I recommend that you create a blank file and open it into memory like this instead of manually trying to build up the file from scratch. That would explain why you are getting so many null pointers.
回答2:
I solve with:
PageSetup pageSetup = worksheetPart.Worksheet.Descendants<PageSetup>().FirstOrDefault();
if (pageSetup == null)
{
pageSetup = new PageSetup();
pageSetup.Orientation = OrientationValues.Landscape;
worksheetPart.Worksheet.AppendChild(pageSetup);
}
来源:https://stackoverflow.com/questions/3237494/how-change-excel-2007-document-orientation-to-landscape-by-openxml-sdk