0

大家好,我有以下行和列的excel

SKU  Quantity  Line Price  Unit Price  Line Discount
XYZ     2          4            2           1

案例2

SKU  Quantity  Line Price  Unit Price  Line Discount
XYZ     2                                 1

如果执行 Line Discount 后的 case2 值显示在 Line Price 中

public static DataSet LoadExcelData(string pUserID, string pFilePath)
    {
            DataSet lDSExcel = new DataSet();
            DataTable lDTExcel = new DataTable();

            using (SpreadsheetDocument spreadSheetDocument = SpreadsheetDocument.Open(pFilePath, 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;
                SheetData sheetData = workSheet.GetFirstChild<SheetData>();
                IEnumerable<Row> rows = sheetData.Descendants<Row>();

                foreach (Cell cell in rows.ElementAt(0))
                {
                    lDTExcel.Columns.Add(GetCellValue(spreadSheetDocument, cell));
                }

                foreach (Row row in rows)
                {
                    DataRow tempRow = lDTExcel.NewRow();

                    for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
                    {
                        tempRow[i] = GetCellValue(spreadSheetDocument, row.Descendants<Cell>().ElementAt(i));
                    }

                    lDTExcel.Rows.Add(tempRow);
                }
                lDSExcel.Tables.Add(lDTExcel);
            }
            lDTExcel.Rows.RemoveAt(0);
            return lDSExcel;
      }

public static string GetCellValue(SpreadsheetDocument document, Cell cell)
    {
            string value = string.Empty;
            SharedStringTablePart stringTablePart = document.WorkbookPart.SharedStringTablePart;
            //if (cell.CellValue != null)
            //    value = cell.CellValue.InnerXml;

            if (cell.DataType != null && cell.DataType.Value == CellValues.SharedString)
            {
                return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(value)].InnerText;
            }
            else
            {
                return value;
            }
        }
    }

但这是一个例外,有人可以帮助我吗

4

1 回答 1

0

在函数 GetCellValue() 中,将共享字符串返回部分更改为:

return stringTablePart.SharedStringTable.ChildElements[Int32.Parse(cell.CellValue.InnerText)].InnerText;

您正在解析一个空字符串(变量“value”,它是用一个空字符串初始化的)。如果没有初始化,我会给你检查 cell.CellValue 的错误...

于 2013-06-17T03:42:14.253 回答