title: Set Rows to repeat at top when printing - Open XML and Excel
body: <p>I am trying to get the first 4 rows of an xlsx file to repeat at the top of each page when printed.  I am using the Open XML SDK to accomplish this.  </p>
  
  <p>My file is being generated by the SSRS execution web service as a filestream.  I then need to modify several layout and page settings (margins, page size, zoom, etc) before delivering the file to the user, as my users have very little Excel acumen.  All other settings I need to tweak are working correctly, so I have stripped out all of that code from this example.</p>
  
  <p>When trying to set the repeating page headers using the code below, it executes with no errors.  However, when I try to open the file after executing the code, I am getting a corrupt file message and it won't open.  </p>
  
  <p>Any idea what I'm doing wrong here?!  It's driving me crazy!</p>
  
  <pre><code>using (SpreadsheetDocument xl = SpreadsheetDocument.Open("C:\\" + filename, true))
  {
  WorkbookPart wbp = xl.WorkbookPart;
  
  //-----------------------------------------
  // repeat rows at top when printing
  //-----------------------------------------
  DefinedNames dn = new DefinedNames();
  wbp.Workbook.Append(dn);
  wbp.Workbook.Save();
  
  DefinedNames definedNames = wbp.Workbook.Descendants&lt;DefinedNames&gt;().FirstOrDefault();
  DefinedName n1 = new DefinedName() { Name = "_xlnm.Print_Titles", LocalSheetId = (UInt32Value)0U };
  n1.Text = "alpha_sort_nc!$1:$4";
  definedNames.Append(n1);
  wbp.Workbook.Save();
  
  xl.Close();
  }
  </code></pre>