Search code examples
c#excelxmlashx

Excel 2019 throws a XML error when get data from ashx handler


I have an excel file that connect to the ASHX handler. User can update this file on demand. People that uses Excel 2016 (and earlier) have no problem with updating, but Excel 2019 user's get an XML error, when trying to update this file. Error text:

"error in the top-level element of the document".

ASHX code:

public void ProcessRequest(HttpContext context)
{
    var dataProvider = new ReportDataProvider();

    var paramsId = GetParamsId(context);
    var customReportParams = dataProvider.GetParams(paramsId);

    var predifinedParams = new CrossReportPredefinedParams(customReportParams.PredefinedParams);

    var formParams = (customReportParams.FormParams ?? string.Empty)
            .Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries)
            .Select(x =>
            {
                int value;
                return new { Valid = int.TryParse(x, out value), Value = value };
            })
            .Where(x => x.Valid && x.Value > 0)
            .Select(x => x.Value)
            .Distinct()
            .ToArray();

    if (!predifinedParams.IsAnyOneDefined && formParams.Length <= 0)
    {
        ReturnError(context, "Не определены параметры отчёта.");
        return;
    }

    var formId = GetFormId(context);
    var data = dataProvider.GetData(formId, predifinedParams, formParams);
    if (data == null)
    {
        ReturnError(context, "Нет данных для указанной регистрационной формы.");
        return;
    }

    var excelCheat = !string.IsNullOrWhiteSpace(context.Request.Params["ExcelCheat"]);
    if (excelCheat && (data.Rows.Count == 1))
        data.Rows.Add();

    context.Response.ContentType = "text/xml";
    data.WriteXml(context.Response.OutputStream);
}

Any ideas why is this happen when using 2019 Excel and how to fix it?

UPD_1: xml file is valid. I created it instead of returning in output stream and check with xml validator.

UPD_2: xml file:

<NewDataSet>
  <Report>
    <_x2116_>25962</_x2116_>
    <Дата_x0020_последнего_x0020_изменения>14.06.2019 11:52</Дата_x0020_последнего_x0020_изменения>
    <Клиент>*Ромбо</Клиент>
    <Пользователь>Стефанкевич Юлия Владимировна</Пользователь>
    <Статус>Подтверждена</Статус>
    <ФИО>Стефанкевич Юлия Владимировна</ФИО>
    <Название_x0020_компании>ООО "Ромбо-проекты"</Название_x0020_компании>
    <Должность>ассистент менеджера по продажам</Должность>
    <Мобильный_x0020_телефон_x003C_br_x003E__x0028_Пример_x003A__x0020__x002B_7_x0020__x0028_987_x0029__x0020_123_x0020_45_x0020_67_x0029_>+7(906)7105234</Мобильный_x0020_телефон_x003C_br_x003E__x0028_Пример_x003A__x0020__x002B_7_x0020__x0028_987_x0029__x0020_123_x0020_45_x0020_67_x0029_>
    <Адрес_x0020_электронной_x0020_почты>Stefankevich@rombo.ru</Адрес_x0020_электронной_x0020_почты>
  </Report>
</NewDataSet>

UPD_3: I manually added <?xml version="1.0" encoding="UTF-8"?> to xml file that generates ASHX handler, but it didn't help.

            string xmlstr;
            using (var stream = new MemoryStream())
            {
                data.WriteXml(stream);
                stream.Seek(0, SeekOrigin.Begin);
                var sr = new StreamReader(stream);
                xmlstr = sr.ReadToEnd();
                xmlstr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + Environment.NewLine + xmlstr;
            }

            var doc = new XmlDocument();
            doc.LoadXml(xmlstr);

            doc.Save(context.Response.Output);

Solution

  • Well, the real error cause was... Excel trim URL of request to ashx handler. Only 115 symbols, no more. How and why? We (me and my team) don't found out. And this happened not only for 2019 excel users, some people has the same thing with 2016 excel.

    So if you have the same problem, please, check url of sending request from excel (with Fiddler for example).

    p.s.: The excel file is made by our winforms tool for users reports. And this tool uses Microsoft.Office.Interop.Excel library, so we have some suspicions about that.