• 15 апреля стартует «Курс «SQL-injection Master» ©» от команды The Codeby

    За 3 месяца вы пройдете путь от начальных навыков работы с SQL-запросами к базам данных до продвинутых техник. Научитесь находить уязвимости связанные с базами данных, и внедрять произвольный SQL-код в уязвимые приложения.

    На последнюю неделю приходится экзамен, где нужно будет показать свои навыки, взломав ряд уязвимых учебных сайтов, и добыть флаги. Успешно сдавшие экзамен получат сертификат.

    Запись на курс до 25 апреля. Получить промодоступ ...

запись в ХМЛ

  • Автор темы carhun
  • Дата начала
C

carhun

выбивает Excrption на след строчке
public void Convert(IEnumerable tables, string fileName) {
HttpContext.Current.Response.ClearContent();

Пишет в экземпляре объекта не указана ссылка на объект.
Что делать?

Может кто-то может мне помочь это сделать без Респонс, цель функции что бы создать ХМЛ файлик к-ый состоит из данных dataGridView а потом этот файл открыть в екселе.

Или как вообще создать этот объект Response

[codebox]
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Xml;
public void Convert(DataSet ds, string fileName) {
Convert(ds.Tables, fileName);
}
public void Convert(IEnumerable tables, string fileName) {
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AddHeader("content-disposition",
"attachment; filename=" + fileName + ".xls");
using (XmlTextWriter x = new XmlTextWriter(HttpContext.Current.Response.OutputStream, Encoding.UTF8)) {
int sheetNumber = 0;
x.WriteRaw("<?xml version=\"1.0\"?><?mso-application progid=\"Excel.Sheet\"?>");
x.WriteRaw("<Workbook xmlns=\"urn:schemas-microsoft-com:eek:ffice:spreadsheet\" ");
x.WriteRaw("xmlns:eek:=\"urn:schemas-microsoft-com:eek:ffice:eek:ffice\" ");
x.WriteRaw("xmlns:x=\"urn:schemas-microsoft-com:eek:ffice:excel\">");
x.WriteRaw("<Styles><Style ss:ID='sText'>" +
"<NumberFormat ss:Format='@'/></Style>");
x.WriteRaw("<Style ss:ID='sDate'><NumberFormat" +
" ss:Format='[$-409]m/d/yy\\ h:mm\\ AM/PM;@'/>");
x.WriteRaw("</Style></Styles>");
foreach (DataTable dt in tables) {
sheetNumber++;
string sheetName = !string.IsNullOrEmpty(dt.TableName) ?
dt.TableName : "Sheet" + sheetNumber.ToString();
x.WriteRaw("<Worksheet ss:Name='" + sheetName + "'>");
x.WriteRaw("<Table>");
string[] columnTypes = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++) {
string colType = dt.Columns.DataType.ToString().ToLower();
if (colType.Contains("datetime")) {
columnTypes = "DateTime";
x.WriteRaw("<Column ss:StyleID='sDate'/>");
} else if (colType.Contains("string")) {
columnTypes = "String";
x.WriteRaw("<Column ss:StyleID='sText'/>");
} else {
x.WriteRaw("<Column />");
if (colType.Contains("boolean")) {
columnTypes = "Boolean";
} else {
//default is some kind of number.
columnTypes = "Number";
}
}
}
//column headers
x.WriteRaw("<Row>");
foreach (DataColumn col in dt.Columns) {
x.WriteRaw("<Cell ss:StyleID='sText'><Data ss:Type='String'>");
x.WriteRaw(col.ColumnName);
x.WriteRaw("</Data></Cell>");
}
x.WriteRaw("</Row>");
//data
bool missedNullColumn = false;
foreach (DataRow row in dt.Rows) {
x.WriteRaw("<Row>");
for (int i = 0; i < dt.Columns.Count; i++) {
if (!row.IsNull(i)) {
if (missedNullColumn) {
int displayIndex = i + 1;
x.WriteRaw("<Cell ss:Index='" + displayIndex.ToString() +
"'><Data ss:Type='" +
columnTypes + "'>");
missedNullColumn = false;
} else {
x.WriteRaw("<Cell><Data ss:Type='" +
columnTypes + "'>");
}
switch (columnTypes) {
case "DateTime":
x.WriteRaw(((DateTime)row).ToString("s"));
break;
case "Boolean":
x.WriteRaw(((bool)row) ? "1" : "0");
break;
case "String":
x.WriteString(row.ToString());
break;
default:
x.WriteString(row.ToString());
break;
}
x.WriteRaw("</Data></Cell>");
} else {
missedNullColumn = true;
}
}
x.WriteRaw("</Row>");
}
x.WriteRaw("</Table></Worksheet>");
}
x.WriteRaw("</Workbook>");
}
HttpContext.Current.Response.End();
}[/codebox]
 
C

carhun

Да, я уже это понял решил это проблему так. Просто в конструкторе XmlTextWriter напрямую указал местонахожденеи файла...
Теперь есть еще вопрос. Как теперь добавить Автофильтр в XML файлик

Код:
public void Convert(IEnumerable tables, string fileName) {

using (XmlTextWriter x = new XmlTextWriter(fileName, Encoding.UTF8)) {
int sheetNumber = 0;
x.WriteRaw("<?xml version=\"1.0\"?><?mso-application progid=\"Excel.Sheet\"?>");
x.WriteRaw("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" ");
x.WriteRaw("xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
x.WriteRaw("xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
x.WriteRaw("<Styles><Style ss:ID='sText'>" +
"<NumberFormat ss:Format='@'/></Style>");
x.WriteRaw("<Style ss:ID='sDate'><NumberFormat" +
" ss:Format='[$-409]m/d/yy\\ h:mm\\ AM/PM;@'/>");
x.WriteRaw("</Style></Styles>");
foreach (DataTable dt in tables) {
sheetNumber++;
string sheetName = !string.IsNullOrEmpty(dt.TableName) ?
dt.TableName : "Sheet" + sheetNumber.ToString();
x.WriteRaw("<Worksheet ss:Name='" + sheetName + "'>");
x.WriteRaw("<Table>");
string[] columnTypes = new string[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++) {
string colType = dt.Columns[i].DataType.ToString().ToLower();
if (colType.Contains("datetime")) {
columnTypes[i] = "DateTime";
x.WriteRaw("<Column ss:StyleID='sDate'/>");
} else if (colType.Contains("string")) {
columnTypes[i] = "String";
x.WriteRaw("<Column ss:StyleID='sText'/>");
} else {
x.WriteRaw("<Column />");
if (colType.Contains("boolean")) {
columnTypes[i] = "Boolean";
} else {
//default is some kind of number.
columnTypes[i] = "Number";
}
}
}
//column headers
x.WriteRaw("<Row>");
foreach (DataColumn col in dt.Columns) {
x.WriteRaw("<Cell ss:StyleID='sText'><Data ss:Type='String'>");
x.WriteRaw(col.ColumnName);
x.WriteRaw("</Data></Cell>");
}
x.WriteRaw("</Row>");
//data
bool missedNullColumn = false;
foreach (DataRow row in dt.Rows) {
x.WriteRaw("<Row>");
for (int i = 0; i < dt.Columns.Count; i++) {
if (!row.IsNull(i)) {
if (missedNullColumn) {
int displayIndex = i + 1;
x.WriteRaw("<Cell ss:Index='" + displayIndex.ToString() +
"'><Data ss:Type='" +
columnTypes[i] + "'>");
missedNullColumn = false;
} else {
x.WriteRaw("<Cell><Data ss:Type='" +
columnTypes[i] + "'>");
}
switch (columnTypes[i]) {
case "DateTime":
x.WriteRaw(((DateTime)row[i]).ToString("s"));
break;
case "Boolean":
x.WriteRaw(((bool)row[i]) ? "1" : "0");
break;
case "String":
x.WriteString(row[i].ToString());
break;
default:
x.WriteString(row[i].ToString());
break;
}
x.WriteRaw("</Data></Cell>");
} else {
missedNullColumn = true;
}
}
x.WriteRaw("</Row>");
}
x.WriteRaw("</Table></Worksheet>");
}
x.WriteRaw("</Workbook>");
}
}
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!