示例#1
0
        public static void UpdateValue(this WorkbookPart wbPart, string sheetName, string addressName, string value, UInt32Value styleIndex, CellValues dataType, Dictionary <string, int> sharedStrings)
        {
            //   if (string.IsNullOrEmpty(value)) return;
            //throw new NullReferenceException("value is empty.");

            if (addressName.IndexOf('!') != -1)
            {
                sheetName   = addressName.Split('!')[0];
                addressName = addressName.Split('!')[1];
            }
            // Assume failure.

            var sheet = wbPart.Workbook.Descendants <Sheet>().FirstOrDefault(s => s.Name == sheetName);

            if (sheet == null)
            {
                return;
            }

            var ws   = ((WorksheetPart)(wbPart.GetPartById(sheet.Id))).Worksheet;
            var cell = ws.InsertCellInWorksheet(addressName);

            switch (dataType)
            {
            case CellValues.SharedString:
                if (cell.DataType != null && cell.DataType == CellValues.SharedString)
                {
                    // Tengo que remover el anterior; al office no le gustan las huerfanas.
                    var oldIdex = int.Parse(cell.CellValue.Text);
                    cell.CellValue.Text = "-1";
                    wbPart.RemoveSharedStringItem(oldIdex, sharedStrings);
                    ws.Save();
                }

                var stringIndex = wbPart.InsertSharedStringItem(value, sharedStrings);
                cell.CellValue = new CellValue(stringIndex.ToString(CultureInfo.InvariantCulture));
                cell.DataType  = CellValues.SharedString;
                //        System.Diagnostics.Debug.WriteLine(String.Format("{0} {1} {2}" , cell.CellValue.Text , cell ));
                break;

            case CellValues.Boolean:
            case CellValues.Number:
            case CellValues.Error:
            case CellValues.String:
            case CellValues.InlineString:
            case CellValues.Date:
                goto default;

            default:
                cell.CellValue = new CellValue(value);
                break;
            }

            cell.DataType = new EnumValue <CellValues>(dataType);

            if (styleIndex > 0)
            {
                cell.StyleIndex = styleIndex;
            }

            // Save the worksheet.
            //ws.Save();
        }