嘗試引用此鏈接:SheetViews爲null試圖凍結行的OpenXML
我得到這個線的SheetView空指針異常:
的SheetView SW = wsp.Worksheet.SheetViews .FirstOrDefault()asSheetView;
創建我的電子表格時,我沒有使用任何sheetviews,和我使用的MemoryStream傳回使用。
使用此代碼:
我怎麼會凍頂兩行?謝謝!
MemoryStream ms = new MemoryStream();
SpreadsheetDocument xl = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart wbp = xl.AddWorkbookPart();
WorksheetPart wsp = wbp.AddNewPart<WorksheetPart>();
Workbook wb = new Workbook();
FileVersion fv = new FileVersion();
fv.ApplicationName = "Microsoft Office Excel";
Worksheet ws = new Worksheet();
SheetData sd = new SheetData();
WorkbookStylesPart stylesPart = xl.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStyleSheet();
stylesPart.Stylesheet.Save();
//create header
uint colHeaderIndex = 1;
Row r1 = new Row() { RowIndex = colHeaderIndex };
foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(list[0]))
{
Cell headerCell = new Cell();
headerCell.DataType = CellValues.String;
headerCell.CellValue = new CellValue(descriptor.DisplayName);
r1.Append(headerCell);
}
//append header row to sheet
sd.Append(r1);
//now fill the rest of the rows with data
uint rowIndex = 1; //Start at 1, since we reserved index 1 for the heading. The indexer will increase its value by 1 before it is used.
for (int i = 0; i < list.Count; i++)
{
uint colIndex = 1;
Row row = new Row() { RowIndex = ++rowIndex };
foreach (System.ComponentModel.PropertyDescriptor descriptor in System.ComponentModel.TypeDescriptor.GetProperties(list[i]))
{
Cell cell = new Cell();
cell.CellReference = rowIndex + " x " + colIndex;
cell.DataType = CellValues.String;
cell.StyleIndex = 1;
var val = descriptor.GetValue(list[i]);
cell.CellValue = new CellValue(val != null ? val.ToString() : "");
row.Append(cell);
}
//append data row to sheet
sd.Append(row);
}
ws.Append(sd);
wsp.Worksheet = ws;
wsp.Worksheet.Save();
Sheets sheets = new Sheets();
Sheet sheet = new Sheet();
sheet.Name = "first sheet";
sheet.SheetId = 1; //we will only have one sheet for now, unless we are maxing out on sheets then we can create new ones
sheet.Id = wbp.GetIdOfPart(wsp);
sheets.Append(sheet);
wb.Append(fv);
wb.Append(sheets);
freezeHeader(wbp, wsp);
xl.WorkbookPart.Workbook = wb;
xl.WorkbookPart.Workbook.Save();
xl.Close();
Response.Clear();
byte[] dt = ms.ToArray();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", fileName));
Response.BinaryWrite(dt);
Response.End();