Excel 打开 XML 错误:“发现不可读的内容”创建简单示例时

发布于 2024-11-07 13:51:12 字数 2397 浏览 2 评论 0原文

当我尝试打开由以下代码创建的文档时,出现模糊的“excel 发现不可读内容”错误:

public void GenerateWorkbookFromDB()
{
    //Make a copy of the template file
    File.Copy(HttpContext.Current.Server.MapPath("ReportTemplate/test.xlsx"), HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true);

    //Open up the copied template workbook
    using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true))
    {
        WorkbookPart workbookPart = myWorkbook.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        string origninalSheetId = workbookPart.GetIdOfPart(worksheetPart);

        WorksheetPart replacementPart = workbookPart.AddNewPart<WorksheetPart>();
        string replacementPartId = workbookPart.GetIdOfPart(replacementPart);

        OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
        OpenXmlWriter writer = OpenXmlWriter.Create(replacementPart);

        Row r = new Row();
        Cell c = new Cell();
        CellValue v = new CellValue();
        v.Text = "test";
        c.Append(v);

        while (reader.Read())
        {
            if (reader.ElementType == typeof(SheetData))
            {
                if (reader.IsEndElement)
                    continue;
                writer.WriteStartElement(new SheetData());

                for (int row = 0; row < 20; row++)
                {
                    writer.WriteStartElement(r);

                    for (int col = 0; col < 4; col++)
                    {
                        writer.WriteElement(c);
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }
            else
            {
                if (reader.IsStartElement)
                    writer.WriteStartElement(reader);
                else if (reader.IsEndElement)
                    writer.WriteEndElement();
            }
        }
        reader.Close();
        writer.Close();

        try
        {
            Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(origninalSheetId)).First();
            sheet.Id.Value = replacementPartId;
            workbookPart.DeletePart(worksheetPart);
        }
        catch (Exception ex) { }
    }
}

非常感谢任何帮助或建议! :D

I am getting the ambiguous "excel found unreadable content" error when I try to open the document created by the following code:

public void GenerateWorkbookFromDB()
{
    //Make a copy of the template file
    File.Copy(HttpContext.Current.Server.MapPath("ReportTemplate/test.xlsx"), HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true);

    //Open up the copied template workbook
    using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true))
    {
        WorkbookPart workbookPart = myWorkbook.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        string origninalSheetId = workbookPart.GetIdOfPart(worksheetPart);

        WorksheetPart replacementPart = workbookPart.AddNewPart<WorksheetPart>();
        string replacementPartId = workbookPart.GetIdOfPart(replacementPart);

        OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
        OpenXmlWriter writer = OpenXmlWriter.Create(replacementPart);

        Row r = new Row();
        Cell c = new Cell();
        CellValue v = new CellValue();
        v.Text = "test";
        c.Append(v);

        while (reader.Read())
        {
            if (reader.ElementType == typeof(SheetData))
            {
                if (reader.IsEndElement)
                    continue;
                writer.WriteStartElement(new SheetData());

                for (int row = 0; row < 20; row++)
                {
                    writer.WriteStartElement(r);

                    for (int col = 0; col < 4; col++)
                    {
                        writer.WriteElement(c);
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }
            else
            {
                if (reader.IsStartElement)
                    writer.WriteStartElement(reader);
                else if (reader.IsEndElement)
                    writer.WriteEndElement();
            }
        }
        reader.Close();
        writer.Close();

        try
        {
            Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(origninalSheetId)).First();
            sheet.Id.Value = replacementPartId;
            workbookPart.DeletePart(worksheetPart);
        }
        catch (Exception ex) { }
    }
}

any help or suggestions is much appreciated! :D

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

临风闻羌笛 2024-11-14 13:51:12

实际上,我找到了一种通过更改将文本输入单元格本身的方式来修复错误的方法。请注意,在下面的代码中,我注释掉了这两行以及我用什么替换了它们。

public void GenerateWorkbookFromDB()
{
    //Make a copy of the template file
    File.Copy(HttpContext.Current.Server.MapPath("ReportTemplate/test.xlsx"), HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true);

    //Open up the copied template workbook
    using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true))
    {
        WorkbookPart workbookPart = myWorkbook.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        string origninalSheetId = workbookPart.GetIdOfPart(worksheetPart);

        WorksheetPart replacementPart = workbookPart.AddNewPart<WorksheetPart>();
        string replacementPartId = workbookPart.GetIdOfPart(replacementPart);

        OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
        OpenXmlWriter writer = OpenXmlWriter.Create(replacementPart);

        Row r = new Row();
        Cell c = new Cell();
        string txt = "test";
        c.CellValue = new CellValue(txt.ToString());
        c.DataType = new EnumValue<CellValues>(CellValues.String);
        //v.Text = "test";
        //c.Append(v);

        while (reader.Read())
        {
            if (reader.ElementType == typeof(SheetData))
            {
                if (reader.IsEndElement)
                    continue;
                writer.WriteStartElement(new SheetData());

                for (int row = 0; row < 20; row++)
                {
                    writer.WriteStartElement(r);

                    for (int col = 0; col < 4; col++)
                    {
                        writer.WriteElement(c);
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }
            else
            {
                if (reader.IsStartElement)
                    writer.WriteStartElement(reader);
                else if (reader.IsEndElement)
                    writer.WriteEndElement();
            }
        }
        reader.Close();
        writer.Close();

        try
        {
            Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(origninalSheetId)).First();
            sheet.Id.Value = replacementPartId;
            workbookPart.DeletePart(worksheetPart);
        }
        catch (Exception ex) { }
    }
}

我希望这对可能遇到相同问题或类似问题的其他人有所帮助。

感谢那些试图回答的人;-)

I actually found a way to fix the error by changing the way I input the text into the cell itself. Notice in the code below where I commented out the 2 lines and what I replaced them with.

public void GenerateWorkbookFromDB()
{
    //Make a copy of the template file
    File.Copy(HttpContext.Current.Server.MapPath("ReportTemplate/test.xlsx"), HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true);

    //Open up the copied template workbook
    using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(HttpContext.Current.Server.MapPath("Reports/test.xlsx"), true))
    {
        WorkbookPart workbookPart = myWorkbook.WorkbookPart;
        WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();
        string origninalSheetId = workbookPart.GetIdOfPart(worksheetPart);

        WorksheetPart replacementPart = workbookPart.AddNewPart<WorksheetPart>();
        string replacementPartId = workbookPart.GetIdOfPart(replacementPart);

        OpenXmlReader reader = OpenXmlReader.Create(worksheetPart);
        OpenXmlWriter writer = OpenXmlWriter.Create(replacementPart);

        Row r = new Row();
        Cell c = new Cell();
        string txt = "test";
        c.CellValue = new CellValue(txt.ToString());
        c.DataType = new EnumValue<CellValues>(CellValues.String);
        //v.Text = "test";
        //c.Append(v);

        while (reader.Read())
        {
            if (reader.ElementType == typeof(SheetData))
            {
                if (reader.IsEndElement)
                    continue;
                writer.WriteStartElement(new SheetData());

                for (int row = 0; row < 20; row++)
                {
                    writer.WriteStartElement(r);

                    for (int col = 0; col < 4; col++)
                    {
                        writer.WriteElement(c);
                    }

                    writer.WriteEndElement();
                }

                writer.WriteEndElement();
            }
            else
            {
                if (reader.IsStartElement)
                    writer.WriteStartElement(reader);
                else if (reader.IsEndElement)
                    writer.WriteEndElement();
            }
        }
        reader.Close();
        writer.Close();

        try
        {
            Sheet sheet = workbookPart.Workbook.Descendants<Sheet>().Where(s => s.Id.Value.Equals(origninalSheetId)).First();
            sheet.Id.Value = replacementPartId;
            workbookPart.DeletePart(worksheetPart);
        }
        catch (Exception ex) { }
    }
}

I hope this helps anyone else who might be experiencing the same issue or something similar.

Thanks to those who tried to answer ;-)

滥情稳全场 2024-11-14 13:51:12

我希望它对某人有用。

我收到了同样的错误消息,就我而言,原因是工作表名称太长。

Excel 不断将其截断为 31 个字符。因此,一旦我将代码中分配的工作表名称限制为 31 个字符,问题就得到了解决。

I hope it might be useful for somebody.

I got the same error message and in my case the reason turned out to be a too long name of a worksheet.

Excel kept truncating it to 31 character. So once I limited the worksheet name I assigned in code to 31 characters the problem had been resolved.

(り薆情海 2024-11-14 13:51:12

我发现,您需要确保将 Cell 对象添加到行集合时,以正确的顺序放置它们。它们的显示顺序必须与电子表格中显示的顺序相同。例如A2、B2、C2...Z2、AA2、AB2。请注意,如果您尝试比较列的值来放置它们,它们将在 A2 和 B2 之间按 AA2 排序,这将在您尝试打开工作表时导致错误。

What I found was that you need to make sure that when you add the Cell objects to the row collection, that you place them in the proper order. They must appear in the same order that they will show on the spreadsheet. e.g. A2, B2, C2 ... Z2, AA2, AB2. Note that if you try to compare the values of the columns to place them they will sort with AA2 between A2 and B2 which will cause an error whey you try to open the sheet.

偷得浮生 2024-11-14 13:51:12

我通过在单元格上设置正确的类型来纠正它。例如,就我而言,我有两种类型的值:数字和字符串。

 public static void WriteValueOnCell(Cell cell, object value)
    {
        var sValue = value = x.ToString();
        var isValueNumeric = value.GetType().IsNumeric();
        cell.DataType = (isValueNumeric)? CellValues.Number : CellValues.String;
        cell.CellValue = new CellValue(sValue);
    }
    //This example uses this Helper. It informs if an object type is Numeric ;-)
    public static class TypeHelper
    {
        private static readonly HashSet<Type> NumericTypes = new HashSet<Type>
        {
            typeof(int),  typeof(double),  typeof(decimal),
            typeof(long), typeof(short),   typeof(sbyte),
            typeof(byte), typeof(ulong),   typeof(ushort),
            typeof(uint), typeof(float)
        };

        public static bool IsNumeric(this Type myType)
        {
            return NumericTypes.Contains(Nullable.GetUnderlyingType(myType) ?? myType);
        }
    }

I corrected it by setting the correct type on Cell. For instance, in my case I have two types of values: Numerics and Strings.

 public static void WriteValueOnCell(Cell cell, object value)
    {
        var sValue = value = x.ToString();
        var isValueNumeric = value.GetType().IsNumeric();
        cell.DataType = (isValueNumeric)? CellValues.Number : CellValues.String;
        cell.CellValue = new CellValue(sValue);
    }
    //This example uses this Helper. It informs if an object type is Numeric ;-)
    public static class TypeHelper
    {
        private static readonly HashSet<Type> NumericTypes = new HashSet<Type>
        {
            typeof(int),  typeof(double),  typeof(decimal),
            typeof(long), typeof(short),   typeof(sbyte),
            typeof(byte), typeof(ulong),   typeof(ushort),
            typeof(uint), typeof(float)
        };

        public static bool IsNumeric(this Type myType)
        {
            return NumericTypes.Contains(Nullable.GetUnderlyingType(myType) ?? myType);
        }
    }
我的黑色迷你裙 2024-11-14 13:51:12

在工作簿中,数据字段中是否有保留的字符?例如“<”或“>”?我在 XML 解析中见过这种情况,因此它可能是非法字符。我不知道您的情况是否允许,但是 HTTPUtility.HTMLEncode 可以工作吗?

in the workbook, are there any characters that are reserved in the data fields? such as '<' or '>'? I've seen that happen with XML parsing, so it could be an illegal character. I don't know if your circumstances permit it, but would HTTPUtility.HTMLEncode work?

过气美图社 2024-11-14 13:51:12

对我有用的是修改 web.config 文件。

我输入了 maxRequestLength 和executionTimeout,之后效果很好!

在 System.Web 下,输入以下内容:

httpRuntime requestValidationMode="2.0" maxRequestLength="1048576" executionTimeout="600"

尝试一下,看看是否有帮助。

What worked for me was to modify the web.config file.

I put in a maxRequestLength and executionTimeout and it worked fine after that!

under System.Web, put the following:

httpRuntime requestValidationMode="2.0" maxRequestLength="1048576" executionTimeout="600"

Give it a try and see if it helps.

盛夏已如深秋| 2024-11-14 13:51:12

我遇到了这个问题,在使用 SDK 工具后,我发现 CellValues.Date 实际上不受支持。如果您尝试将单元格格式设置为具有适当的数据类型并且收到此消息,请尝试将日期单元格保留为 CellValues.String。

I had this issue and after using the SDK tool I discovered that CellValues.Date isn't actually supported. If you're trying to format your cells to have the appropriate DataType and you're getting this message, try leaving your date cells as CellValues.String.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文