title: Set Print Area - OpenXML with Excel
body: <p>Does anybody know how to set print area through OpenXML SDK in Excel?</p>
  
  <p>I've tried using the following code:</p>
  
  <pre><code>public void XLUpdateDefinedName(string fileName, string definedName, string newRange)
  {
      using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, true))
      {
          WorkbookPart wbPart = document.WorkbookPart;
  
          var definedNames = wbPart.Workbook.Descendants&lt;DefinedNames&gt;().FirstOrDefault();
          DefinedName name = definedNames.Descendants&lt;DefinedName&gt;().Where(m =&gt; m.Name == definedName).Single();
          UInt32Value locSheetId = name.LocalSheetId;
          name = null;//.Remove();
          wbPart.Workbook.Save();
          name = new DefinedName() { Name = definedName, LocalSheetId = locSheetId , Text = newRange}
              ;
          wbPart.Workbook.Save();
          //newDefinedName.Text = newRange;
          //definedNames.Append(newDefinedName);
  
      }
  }
  </code></pre>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>I continue to receive an error from excel saying there is unreadable content in file with the following code.</p>
  
  <pre><code>   public void XLUpdateDefinedName(string fileName, string definedName, string newRange, string sheet, UInt32Value localId)
      {
          using (SpreadsheetDocument document = SpreadsheetDocument.Open(fileName, true))
          {                
              String sheetName = sheet;
              string topLeft = newRange.Split(':').First();
              string bottomRight = newRange.Split(':').Last();
              WorkbookPart wbPart = document.WorkbookPart;
  
              var definedNames = wbPart.Workbook.Descendants&lt;DefinedNames&gt;().FirstOrDefault();
              var nameCollection = definedNames.Descendants&lt;DefinedName&gt;().Where(m =&gt; m.Text.StartsWith(sheetName));
              DefinedName name = nameCollection.Count() &gt; 0 ? nameCollection.First() : null;
              UInt32Value locSheetId;
              if (name != null)
              {
                  locSheetId = name.LocalSheetId;
                  name.Remove();
                  wbPart.Workbook.Save();
              }
              else
              {
                  locSheetId = localId;
              }
              name = new DefinedName() { Name = "_xlnm.Print_Area", LocalSheetId = locSheetId};
              name.Text = String.Format("{0}!{1}:{2}", sheetName,topLeft,bottomRight);
              definedNames.Append(name);
              wbPart.Workbook.Save();
          }}
  </code></pre>
  
  <p>newRange is of the form ( $A$10:$C$15 )</p>