I'm using 'ExcelDataReader' to read in an Excel file, I want to display the file on screen.
protected void Page_Load(object sender, EventArgs e)
{
string filePath = #"C:\WORK\BoireannSVN\trunk\VS\CRCConnect\Spreadsheet\Spreadsheet.xlsx";
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
while (excelReader.Read())
{
Label x = new Label();
x.Text = result.Tables[0].Rows[0].ItemArray[0].ToString();
uploadExcel.Controls.Add(x);
excelReader.GetInt32(0);
}
excelReader.Close();
}
I've added in the
Label x = new Label();
x.Text = result.Tables[0].Rows[0].ItemArray[0].ToString();
Attempting to get the excel sheet to display on screen, although I'm having no luck with this. I think it is something like
table1.Columns.Add;
table1.Rows.Add;
but can't seem to get it going, any help much appreciated.
I was in a similar situation I did the following:
var rows = results.Tables[0].AsEnumerable();
Then you can iterate and select the value for columns:
foreach (var dataRow in rows)
{
Console.WriteLine(dataRow[0]);
//or
Console.WriteLine(dataRow["ColumnName"]);
}
Related
I am new to this so bear with me.
I am trying to create an application that can open a file, load it and then populate the data into a table.
I have managed to hardcode it to the test file I wanted but now need to be able to open any file of the same extension.
The code I have so far is included.
Appreciate if someone could point me in the right direction :)
Thanks, Jo
OpenFileDialog ofd = new OpenFileDialog();
private void Button3_Click(object sender, EventArgs e)
{
ofd.Filter = "evtx|*.evtx"; //Only allows evtx file types to be seen and opened
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
}
private void loadFileButton_Click(object sender, EventArgs e)
{
var dt = new DataTable();
dt.Columns.Add("Level");
dt.Columns.Add("Logname");
dt.Columns.Add("Event ID");
dt.Columns.Add("Date and Time");
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
EventRecord record;
while ((record = reader.ReadEvent()) != null)
{
using (record)
{
dt.Rows.Add(record.Level, record.LogName, record.RecordId, record.TimeCreated.Value.ToString("dd/MM/yyyy tt:hh:mm:ss"));
}
}
}
tblLogViewer.DataSource = dt;
}
If I understand what your issue is, you are prompting for a file in Button3_Click() with...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
}
...but then in loadFileButton_Click() you are using a different path to construct an EventLogReader...
using (var reader = new EventLogReader(#"C:\Users\Jason\Desktop\Event logs\Security.evtx", PathType.FilePath))
{
You are already saving the selected file's path to fileNameTextBox.Text, so just pass that property to the EventLogReader constructor instead...
using (var reader = new EventLogReader(fileNameTextBox.Text, PathType.FilePath))
{
Note that loadFileButton_Click assumes that ofd has previously been displayed and accepted (not canceled). Without knowing what your different buttons are, it might be better to create and use your EventLogReader immediately after successfully prompting for an input file...
if (ofd.ShowDialog() == DialogResult.OK) //Opens the file dialog on button click
{
this.fileNameTextBox.Text = ofd.FileName;
saveFileNameTextBox.Text = ofd.SafeFileName;
using (var reader = new EventLogReader(ofd.FileName, PathType.FilePath))
{
// Use reader...
}
}
I used this code to open the HTML page in HTML editor in c#.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Multiselect =
false, ValidateNames = true, Filter = "HTML|*.html" })
if (ofd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = ofd.FileName;
FileStream fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
webBrowser1.DocumentStream = fs;
}
}
and also I used this code to save the changes
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog svf = new SaveFileDialog();
svf.Filter = "Text Files (.html)|*.html";
if (svf.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter sw = new System.IO.StreamWriter(svf.FileName);
sw.WriteLine(webBrowser1);
sw.Close();
}
}
However, the only line is saved in my HTML page is this message: System.Windows.Forms.WebBrowser.
Do you have any idea that how can I save the content of the HTML page? Thanks
The following should work as you require:
System.IO.StreamWriter sw = new System.IO.StreamWriter(svf.FileName);
webBrowser1.DocumentStream.CopyTo(sw.BaseStream);
sw.Flush();
sw.Close();
The reason yours does not work is because you're trying to write an object to a stream directly, which as stated implicitly calls the ToString() method.
I'm working on an assignment and I'm trying to either convert an image to base64 but after trying some examples on here I get an error message saying the bytes can't exceed infinity, and someone in class suggested I should export the image path instead.
below is the code I have to open the image
private void button1_Click(object sender, EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "PNG Files (.png)|*.png|JPEG Files (.jpg)|*.jpg";
openFileDialog1.FilterIndex = 2;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
Bitmap loadedImage = new Bitmap(openFileDialog1.FileName);
setImage.Size = loadedImage.Size;
setImage.BackgroundImage = loadedImage;
imageWidth.Text = loadedImage.Size.Width.ToString();
imageHeight.Text = loadedImage.Size.Height.ToString();
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
after opening the Image I need to be able to export the dimensions of the image to XML but I also want to export the image path there as well.
Below is the code I'm using to export as you can see I haven't done the image export as I'm unsure what to do there
private void exportButton_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
DataTable xyPos = new DataTable();
xyPos.TableName = "Position";
xyPos.Columns.Add("X");
xyPos.Columns.Add("Y");
ds.Tables.Add(xyPos);
DataTable whDimen = new DataTable();
whDimen.TableName = "Dimensions";
whDimen.Columns.Add("Width");
whDimen.Columns.Add("Height");
ds.Tables.Add(whDimen);
DataTable loadImage = new DataTable();
loadImage.TableName = "LoadedImage";
loadImage.Columns.Add("Image");
ds.Tables.Add(loadImage);
DataRow posRow = ds.Tables["Position"].NewRow();
posRow["X"] = Xcoord.Text;
posRow["Y"] = Ycoord.Text;
ds.Tables["Position"].Rows.Add(posRow);
DataRow dimenRow = ds.Tables["Dimensions"].NewRow();
dimenRow["Width"] = imageWidth.Text;
dimenRow["Height"] = imageHeight.Text;
ds.Tables["Dimensions"].Rows.Add(dimenRow);
//Export Image
DataRow imageRow = ds.Tables["LoadedImage"].NewRow();
imageRow["Image"] = setImage.BackgroundImage;
//ImageConverter imgConvert = new ImageConverter();
//byte[] imgByte = (byte[])imgConvert.ConvertTo(imageRow["Image"], typeof(byte[]));
//Convert.ToBase64String(imgByte);
//Convert.ToBase64String((byte[])imageRow["Image"]);
ds.Tables["LoadedImage"].Rows.Add(imageArray);
ds.WriteXml("XMLFile1.xml");
}
I have created a few charts dynamically and would like to export the data to excel using closedxml.
I created a custom item on legend and when I click it, the page posts back and the event handler was raised properly. But I couldn't get the save window to pop up, hence not being able to save the excel file. Help me please?
I am using C# on asp.NET Framework 4.5.
Here's a simplified version of my code.
protected void Page_Load(object sender, EventArgs e)
{
Add_Chart();
}
public void Add_Chart()
{
System.Web.UI.DataVisualization.Charting.Chart Add_Chart1 = new System.Web.UI.DataVisualization.Charting.Chart();
//Create Chart here
//Add chart to htmltablecell
Add_Chart1.Click += Chart_Legend_Click;
}
protected void Chart_Button_Click(object sender, ImageMapEventArgs e)
{
string sheetname = "trial";
string filename = "trial.xlsx";
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add(sheetname);
HttpResponse httpResponse = Response;
httpResponse.Clear();
httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
httpResponse.AddHeader("content-disposition", "attachment;filename=" + filename);
//Create header and data rows here
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
workbook.SaveAs(memoryStream);
memoryStream.WriteTo(httpResponse.OutputStream);
memoryStream.Close();
}
httpResponse.End();
}
I'm trying to save ListBox items in text file.
The Items I have added from properties:
My code is:
private void button1_Click(object sender, EventArgs e)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
using (StreamWriter st = new StreamWriter(S))
foreach (string aa in listBox1.Items)
st.WriteLine(listBox1.Items);
}
}
The output in text file is: System.Windows.Forms.ListBox+ObjectCollection
As #davidsbro mentioned, you want aa to be in the st.Writeline as that is the actual string. listBox1.Items gives a class which Writeline can't handle as it doesn't know what you would want from Items. So it outputs the name which is the result you got. If you want all the properties and other information about that Items class you would have to serialize it and write to the file.
Just use the aa into writeLine
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (FileStream S = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
{
using (StreamWriter st = new StreamWriter(S))
{
foreach (var aa in listBox1.Items)
st.WriteLine(aa.ToString());
}
}
}