0
我在ASP.Net中使用DocumentFormat.OpenXml
創建Excel
。如何在Excel中創建多個工作表?
任何人都可以有想法如何在Excel中創建多個工作表。
例如,工作表Sheet1,Sheet2中,工作表Sheet 3 ...... sheetn
我在ASP.Net中使用DocumentFormat.OpenXml
創建Excel
。如何在Excel中創建多個工作表?
任何人都可以有想法如何在Excel中創建多個工作表。
例如,工作表Sheet1,Sheet2中,工作表Sheet 3 ...... sheetn
試試下面的方法:
/// <summary>
/// Add a blank worksheet to the workbook
/// </summary>
/// <param name="workbookPart">Wookbook part</param>
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{
// Add a blank WorksheetPart.
WorksheetPart newWorksheetPart = workbookPart.AddNewPart<WorksheetPart>();
// Create the new worksheet
Worksheet worksheet = new Worksheet();
worksheet.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
SheetDimension sheetDimension1 = new SheetDimension() { Reference = "A1" };
SheetViews sheetViews1 = new SheetViews();
SheetView sheetView1 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };
sheetViews1.Append(sheetView1);
SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 15D };
SheetData sheetData1 = new SheetData();
PageMargins pageMargins1 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };
PageSetup pageSetup1 = new PageSetup() { Orientation = OrientationValues.Portrait, Id = "rId1" };
worksheet.Append(sheetDimension1);
worksheet.Append(sheetViews1);
worksheet.Append(sheetFormatProperties1);
worksheet.Append(sheetData1);
worksheet.Append(pageMargins1);
worksheet.Append(pageSetup1);
newWorksheetPart.Worksheet = worksheet;
newWorksheetPart.Worksheet.Save();
Sheets sheets = workbookPart.Workbook.GetFirstChild<Sheets>();
string relationshipId = workbookPart.GetIdOfPart(newWorksheetPart);
// Get a unique ID for the new worksheet.
uint sheetId = 1;
if (sheets.Elements<Sheet>().Count() > 0)
{
sheetId = sheets.Elements<Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
// Give the new worksheet a name.
string sheetName = "Sheet" + sheetId;
// Append the new worksheet and associate it with the workbook.
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = sheetName };
sheets.Append(sheet);
workbookPart.Workbook.Save();
}
編輯
這裏是包含方法的類:
public static class ExcelHelpers
{
public static void InsertBlankWorksheet(WorkbookPart workbookPart)
{...}
}
打開你的Excel文檔,並調用方法:
public static void Export(string document)
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(document, true))
{
ExcelHelpers.InsertBlankWorksheet(doc.WorkbookPart);
}
}
感謝您提供代碼,請讓我知道如何調用InsertBlankWorksheet()函數。 – 2011-06-14 08:53:53
@Pankaj - 查看我的編輯 – amurra 2011-06-14 12:27:40
非常感謝......它的工作原理 – 2011-06-14 12:59:37