在c#中读取使用openxml创建的excel文件时出错

时间:2014-08-26 10:17:12

标签: c# asp.net excel openxml

我正在使用open xml创建.xlsx文件。当我尝试读取使用openxml创建的同一文件时,无法正确识别。如果我再次保存我的文件并尝试阅读它,问题就会消失,所以我认为它可能与我创建文件的方式有关。任何建议,将不胜感激。这是我用来生成文件的代码。

 public void CreatePackage(string filePath)
    {
        using (SpreadsheetDocument package = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
        {
            CreateParts(package);
        }
    }

    public void CreatePackage(MemoryStream mStream)
    {
        using (SpreadsheetDocument package = SpreadsheetDocument.Create(mStream, SpreadsheetDocumentType.Workbook))
        {
            CreateParts(package);
        }
    }

    // Adds child parts and generates content of the specified part.
    private void CreateParts(SpreadsheetDocument document)
    {
        ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId3");
        GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1);

        WorkbookPart workbookPart1 = document.AddWorkbookPart();
        GenerateWorkbookPart1Content(workbookPart1);

        WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>("rId3");
        GenerateWorksheetPart1Content(worksheetPart1);

        WorksheetPart worksheetPart2 = workbookPart1.AddNewPart<WorksheetPart>("rId2");
        GenerateWorksheetPart2Content(worksheetPart2);

        WorksheetPart worksheetPart3 = workbookPart1.AddNewPart<WorksheetPart>("rId1");
        GenerateWorksheetPart3Content(worksheetPart3);

        SpreadsheetPrinterSettingsPart spreadsheetPrinterSettingsPart1 = worksheetPart3.AddNewPart<SpreadsheetPrinterSettingsPart>("rId1");
        GenerateSpreadsheetPrinterSettingsPart1Content(spreadsheetPrinterSettingsPart1);

        WorkbookStylesPart workbookStylesPart1 = workbookPart1.AddNewPart<WorkbookStylesPart>("rId5");
        GenerateWorkbookStylesPart1Content(workbookStylesPart1);

        //ThemePart themePart1 = workbookPart1.AddNewPart<ThemePart>("rId4");
        //GenerateThemePart1Content(themePart1);

        SetPackageProperties(document);
    }

    // Generates content of extendedFilePropertiesPart1.
    private void GenerateExtendedFilePropertiesPart1Content(ExtendedFilePropertiesPart extendedFilePropertiesPart1)
    {
        Ap.Properties properties1 = new Ap.Properties();
        properties1.AddNamespaceDeclaration("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
        Ap.Application application1 = new Ap.Application();
        application1.Text = "Microsoft Excel";
        Ap.DocumentSecurity documentSecurity1 = new Ap.DocumentSecurity();
        documentSecurity1.Text = "0";
        Ap.ScaleCrop scaleCrop1 = new Ap.ScaleCrop();
        scaleCrop1.Text = "false";

        Ap.HeadingPairs headingPairs1 = new Ap.HeadingPairs();

        Vt.VTVector vTVector1 = new Vt.VTVector() { BaseType = Vt.VectorBaseValues.Variant, Size = (UInt32Value)2U };

        Vt.Variant variant1 = new Vt.Variant();
        Vt.VTLPSTR vTLPSTR1 = new Vt.VTLPSTR();
        vTLPSTR1.Text = "Worksheets";

        variant1.Append(vTLPSTR1);

        Vt.Variant variant2 = new Vt.Variant();
        Vt.VTInt32 vTInt321 = new Vt.VTInt32();
        vTInt321.Text = "3";

        variant2.Append(vTInt321);

        vTVector1.Append(variant1);
        vTVector1.Append(variant2);

        headingPairs1.Append(vTVector1);

        Ap.TitlesOfParts titlesOfParts1 = new Ap.TitlesOfParts();

        Vt.VTVector vTVector2 = new Vt.VTVector() { BaseType = Vt.VectorBaseValues.Lpstr, Size = (UInt32Value)3U };
        Vt.VTLPSTR vTLPSTR2 = new Vt.VTLPSTR();
        vTLPSTR2.Text = "Sheet1";
        Vt.VTLPSTR vTLPSTR3 = new Vt.VTLPSTR();
        vTLPSTR3.Text = "Sheet2";
        Vt.VTLPSTR vTLPSTR4 = new Vt.VTLPSTR();
        vTLPSTR4.Text = "Sheet3";

        vTVector2.Append(vTLPSTR2);
        vTVector2.Append(vTLPSTR3);
        vTVector2.Append(vTLPSTR4);

        titlesOfParts1.Append(vTVector2);
        Ap.Company company1 = new Ap.Company();
        company1.Text = "PricewaterhouseCoopers";
        Ap.LinksUpToDate linksUpToDate1 = new Ap.LinksUpToDate();
        linksUpToDate1.Text = "false";
        Ap.SharedDocument sharedDocument1 = new Ap.SharedDocument();
        sharedDocument1.Text = "false";
        Ap.HyperlinksChanged hyperlinksChanged1 = new Ap.HyperlinksChanged();
        hyperlinksChanged1.Text = "false";
        Ap.ApplicationVersion applicationVersion1 = new Ap.ApplicationVersion();
        applicationVersion1.Text = "12.0000";

        properties1.Append(application1);
        properties1.Append(documentSecurity1);
        properties1.Append(scaleCrop1);
        properties1.Append(headingPairs1);
        properties1.Append(titlesOfParts1);
        properties1.Append(company1);
        properties1.Append(linksUpToDate1);
        properties1.Append(sharedDocument1);
        properties1.Append(hyperlinksChanged1);
        properties1.Append(applicationVersion1);

        extendedFilePropertiesPart1.Properties = properties1;
    }

    // Generates content of workbookPart1.
    private void GenerateWorkbookPart1Content(WorkbookPart workbookPart1)
    {
        Workbook workbook1 = new Workbook();
        workbook1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        FileVersion fileVersion1 = new FileVersion() { ApplicationName = "xl", LastEdited = "4", LowestEdited = "4", BuildVersion = "4506" };
        WorkbookProperties workbookProperties1 = new WorkbookProperties();

        BookViews bookViews1 = new BookViews();
        WorkbookView workbookView1 = new WorkbookView() { XWindow = 120, YWindow = 60, WindowWidth = (UInt32Value)15255U, WindowHeight = (UInt32Value)8160U };

        bookViews1.Append(workbookView1);
        //new line
        //workbook1.Append(new BookViews(new WorkbookView()));
        workbook1.Append(bookViews1);


        Sheets sheets1 = new Sheets();
        Sheet sheet1 = new Sheet() { Name = "Sheet1", SheetId = (UInt32Value)1U, Id = "rId1" };
        Sheet sheet2 = new Sheet() { Name = "Sheet2", SheetId = (UInt32Value)2U, Id = "rId2" };
        Sheet sheet3 = new Sheet() { Name = "Sheet3", SheetId = (UInt32Value)3U, Id = "rId3" };

        sheets1.Append(sheet1);
        sheets1.Append(sheet2);
        sheets1.Append(sheet3);
        CalculationProperties calculationProperties1 = new CalculationProperties() { CalculationId = (UInt32Value)125725U };

        workbook1.Append(fileVersion1);
        workbook1.Append(workbookProperties1);

        workbook1.Append(sheets1);
        workbook1.Append(calculationProperties1);

        workbookPart1.Workbook = workbook1;
    }

    // Generates content of worksheetPart1.
    private void GenerateWorksheetPart1Content(WorksheetPart worksheetPart1)
    {
        Worksheet worksheet1 = new Worksheet();
        worksheet1.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        SheetDimension sheetDimension1 = new SheetDimension() { Reference = "A1" };

        SheetViews sheetViews1 = new SheetViews();
        SheetView sheetView1 = new SheetView() { WorkbookViewId = (UInt32Value)0U };

        sheetViews1.Append(sheetView1);
        SheetFormatProperties sheetFormatProperties1 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
        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 };

        worksheet1.Append(sheetDimension1);
        worksheet1.Append(sheetViews1);
        worksheet1.Append(sheetFormatProperties1);
        worksheet1.Append(sheetData1);
        worksheet1.Append(pageMargins1);

        worksheetPart1.Worksheet = worksheet1;
    }

    // Generates content of worksheetPart2.
    private void GenerateWorksheetPart2Content(WorksheetPart worksheetPart2)
    {
        Worksheet worksheet2 = new Worksheet();
        worksheet2.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        SheetDimension sheetDimension2 = new SheetDimension() { Reference = "A1" };

        SheetViews sheetViews2 = new SheetViews();
        SheetView sheetView2 = new SheetView() { WorkbookViewId = (UInt32Value)0U };

        sheetViews2.Append(sheetView2);
        SheetFormatProperties sheetFormatProperties2 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };
        SheetData sheetData2 = new SheetData();
        PageMargins pageMargins2 = new PageMargins() { Left = 0.7D, Right = 0.7D, Top = 0.75D, Bottom = 0.75D, Header = 0.3D, Footer = 0.3D };

        worksheet2.Append(sheetDimension2);
        worksheet2.Append(sheetViews2);
        worksheet2.Append(sheetFormatProperties2);
        worksheet2.Append(sheetData2);
        worksheet2.Append(pageMargins2);

        worksheetPart2.Worksheet = worksheet2;
    }


    private void GenerateWorksheetPart3Content(WorksheetPart worksheetPart3)
    {
        Worksheet worksheet3 = new Worksheet();
        worksheet3.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        SheetDimension sheetDimension3 = new SheetDimension() { Reference = "A1" };

        SheetViews sheetViews3 = new SheetViews();
        SheetView sheetView3 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };

        sheetViews3.Append(sheetView3);
        SheetFormatProperties sheetFormatProperties3 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };

        Columns columns1 = new Columns();
        Column column1 = new Column() { Min = (UInt32Value)1U, Max = (UInt32Value)52U, Width = 20.7109375D, CustomWidth = true };

        columns1.Append(column1);

        SheetData sheetData3 = new SheetData();

        Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)1U };

        row1.Append(cell1);

        sheetData3.Append(row1);

        /*

        Row row2 = new Row() { RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell2 = new Cell() { CellReference = "B2", StyleIndex = (UInt32Value)1U };

        row2.Append(cell2);

        sheetData3.Append(row2);


        Row row3 = new Row() { RowIndex = (UInt32Value)3U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell3 = new Cell() { CellReference = "C3", StyleIndex = (UInt32Value)2U };

        row3.Append(cell3);
        sheetData3.Append(row3);
        */

        PageMargins pageMargins3 = 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" };

        worksheet3.Append(sheetDimension3);
        worksheet3.Append(sheetViews3);
        worksheet3.Append(sheetFormatProperties3);
        worksheet3.Append(columns1);
        worksheet3.Append(sheetData3);
        worksheet3.Append(pageMargins3);
        worksheet3.Append(pageSetup1);

        worksheetPart3.Worksheet = worksheet3;
    }

    // Generates content of worksheetPart3.
    private void GenerateWorksheetPart3ContentNew(WorksheetPart worksheetPart3)
    {

        Worksheet worksheet3 = new Worksheet();
        worksheet3.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
        SheetDimension sheetDimension3 = new SheetDimension() { Reference = "A1" };

        SheetViews sheetViews3 = new SheetViews();
        SheetView sheetView3 = new SheetView() { TabSelected = true, WorkbookViewId = (UInt32Value)0U };

        sheetViews3.Append(sheetView3);
        SheetFormatProperties sheetFormatProperties3 = new SheetFormatProperties() { DefaultRowHeight = 12.75D };

        Columns columns1 = new Columns();
        Column column1 = new Column() { Min = (UInt32Value)1U, Max = (UInt32Value)52U, Width = 20.7109375D, CustomWidth = true };

        columns1.Append(column1);
        string[] cellname = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
        SheetData sheetData3 = new SheetData();
        int counter = 1;
        Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)1U };
        row1.Append(cell1);
        sheetData3.Append(row1);
        /*
        int counter = 1;
        Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };

        foreach (string cell in cellname)
        {
            string cellId = cell + counter;
            Cell cell1 = new Cell() { CellReference = cellId, StyleIndex = (UInt32Value)1U };
            row1.Append(cell1);

        }
        sheetData3.Append(row1);
        */
        /*
        Row row1 = new Row() { RowIndex = (UInt32Value)1U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };

        string[] cellname = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };


        Cell cell1 = new Cell() { CellReference = "A1", StyleIndex = (UInt32Value)2U };
        row1.Append(cell1);
        Cell cell12 = new Cell() { CellReference = "B1", StyleIndex = (UInt32Value)2U };
        row1.Append(cell12);
        Cell cell13 = new Cell() { CellReference = "C1", StyleIndex = (UInt32Value)2U };
        row1.Append(cell13);
        //Cell cell21 = new Cell() { CellReference = "A2", StyleIndex = (UInt32Value)2U };
        //Cell cell31 = new Cell() { CellReference = "A3", StyleIndex = (UInt32Value)2U };
        //Cell cell41 = new Cell() { CellReference = "A4", StyleIndex = (UInt32Value)2U };
        //row1.StyleIndex = (UInt32Value)2U;

        //row1.Append(cell21);
        //row1.Append(cell31);
        //row1.Append(cell41);

        sheetData3.Append(row1);
        */
        counter = 2;
        Row row2 = new Row() { RowIndex = (UInt32Value)2U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell2 = new Cell() { CellReference = "B2", StyleIndex = (UInt32Value)1U };

        row2.Append(cell2);

        sheetData3.Append(row2);

        counter = 3;
        Row row3 = new Row() { RowIndex = (UInt32Value)3U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell3 = new Cell() { CellReference = "C3", StyleIndex = (UInt32Value)2U };

        row3.Append(cell3);
        sheetData3.Append(row3);

        counter = 4;
        Row row4 = new Row() { RowIndex = (UInt32Value)4U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell4 = new Cell() { CellReference = "D4", StyleIndex = (UInt32Value)2U };
        row4.Append(cell4);
        sheetData3.Append(row4);

        counter = 5;
        Row row5 = new Row() { RowIndex = (UInt32Value)5U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        foreach (string cell in cellname)
        {
            string cellId = cell + counter;
            Cell cell5 = new Cell() { CellReference = cellId, StyleIndex = (UInt32Value)2U };
            row5.Append(cell5);

        }
        sheetData3.Append(row5);

        counter = 6;
        Row row6 = new Row() { RowIndex = (UInt32Value)6U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell6 = new Cell() { CellReference = "F6", StyleIndex = (UInt32Value)1U };
        row6.Append(cell6);
        sheetData3.Append(row6);

        counter = 7;
        Row row7 = new Row() { RowIndex = (UInt32Value)7U, Spans = new ListValue<StringValue>() { InnerText = "1:1" } };
        Cell cell7 = new Cell() { CellReference = "G7", StyleIndex = (UInt32Value)1U };
        row7.Append(cell7);
        sheetData3.Append(row7);

        PageMargins pageMargins3 = 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" };

        worksheet3.Append(sheetDimension3);
        worksheet3.Append(sheetViews3);
        worksheet3.Append(sheetFormatProperties3);
        worksheet3.Append(columns1);
        worksheet3.Append(sheetData3);
        worksheet3.Append(pageMargins3);
        worksheet3.Append(pageSetup1);

        worksheetPart3.Worksheet = worksheet3;
    }

以下是我用于阅读excel文件的代码

public static DataTable ExtractExcelToDataTable(Stream filename)
    {

        DataTable dt = new DataTable();
        string value = string.Empty;

        //MemoryStream stream = new MemoryStream();
        //stream.Write(filename1, 0, filename1.Length);
        try
        {


            using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(filename, false))
            //using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(stream, false))
            {
                /*
                WorkbookPart workbookPart = spreadSheetDocument.WorkbookPart;
                IEnumerable<Sheet> sheets = spreadSheetDocument.WorkbookPart.Workbook.GetFirstChild<Sheets>().Elements<Sheet>();
                string relationshipId = sheets.First().Id.Value;
                WorksheetPart worksheetPart = (WorksheetPart)spreadSheetDocument.WorkbookPart.GetPartById(relationshipId);
                Worksheet workSheet = worksheetPart.Worksheet;
                */

                WorkbookPart workbook = spreadSheetDocument.WorkbookPart;
                //create a reference to Sheet1 
                WorksheetPart workSheet = workbook.WorksheetParts.Last();
                SheetData sheetData = workSheet.Worksheet.GetFirstChild<SheetData>();



                //SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();
                int RowIndex = 0;


                foreach (var row in rows)
                {
                    //Create the data table header row ie columns using first excel row.
                    if (RowIndex == 0)
                    {
                        //CreateColumnsFromHeaderRow(row, dt);
                        foreach (Cell cell in rows.ElementAt(0))
                        {
                            dt.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                        }
                        RowIndex++;
                    }
                    else
                    {
                        //From second row of excel onwards, add data rows to data table.
                        IEnumerable<Cell> cells = GetCellsFromRowIncludingEmptyCells(row);
                        DataRow newDataRow = dt.NewRow();
                        int columnCount = 0;
                        foreach (Cell currentCell in cells)
                        {
                            value = GetCellValue(spreadSheetDocument, currentCell);
                            //There are empty headers which are not added to data table columns. So avoid those.
                            if (columnCount < dt.Columns.Count)
                            {
                                newDataRow[columnCount++] = value;
                            }
                        }
                        dt.Rows.Add(newDataRow);
                    }
                }
                //dt.Rows.RemoveAt(0);
                //remove empty rows
                //DataTable filteredDataTable = (dt.Rows.Cast<DataRow>().Where(row => row.ItemArray.Any(field => !(field is DBNull)))).CopyToDataTable<DataRow>();
                DataTable filteredDataTable = new DataTable();

                if (dt != null && dt.Rows.Count > 0)
                {
                    filteredDataTable = (dt.Rows.Cast<DataRow>().Where(row => row.ItemArray.Any(field => (field.ToString() != string.Empty && field != null)))).CopyToDataTable<DataRow>();
                }

                return filteredDataTable;

            }
        }
        catch (Exception ex)
        {
            throw ex;

        }

    }


 public static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
        SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
        string value = string.Empty;
        if (cell != null)
        {
            if (cell.CellValue != null)
            {
                value = cell.CellValue.InnerXml;
                if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
                {
                    value = stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
                    //Remove new line character
                    value = value.Replace("\n", "").Trim();
                }


            }
        }
        return value;
    }

0 个答案:

没有答案