I am trying to generate a chart for a powerpoint slide using C#.net. The chart works perfectly when I hard code the data, so my goal here is to be able to populate the excel backend from my applications datatable. What i need help with is defining the data ranges(see below)
var areaworkbook = (EXCEL.Workbook)areachart.ChartData.Workbook;
areaworkbook.Windows.Application.Visible = false;
var dataSheet2 = (EXCEL.Worksheet)areaworkbook.Worksheets[1];
var sc2 = areachart.SeriesCollection();
dataSheet1.Cells.Range["A2"].Value2 = "Name 1";
dataSheet1.Cells.Range["A3"].Value2 = "Name 2";
dataSheet1.Cells.Range["A4"].Value2 = "Name 3";
dataSheet1.Cells.Range["A5"].Value2 = "Name 4";
dataSheet1.Cells.Range["B2"].Value2 = Value 1;
dataSheet1.Cells.Range["B3"].Value2 = value 2;
dataSheet1.Cells.Range["B4"].Value2 = value 3;
dataSheet1.Cells.Range["B5"].Value2 = value 4 ;
var series2 = sc2.NewSeries();
series2.Name = "Series 2";
series2.XValues = "'Sheet1'!$A$2:$A$5";
series2.Values = "'Sheet1'!$C$2:$C$5";
series2.ChartType = Office.XlChartType.xlAreaStacked;
areachart.HasTitle = true;
areachart.ChartTitle.Font.Bold = true;
areachart.ChartTitle.Font.Italic = true;
areachart.ApplyLayout(4);
areachart.Refresh();
How will I dynamically add A6, A7, A8... until my datatable is complete?
Just use a loop and calculate the cell address. For the sake of argument, I'm going to assume the data is coming from a Linq query, though you could get it any other way.
int row = 2; // You expect to start here
foreach (var data in db.MyData().Where(... whatever you need here ...))
{
dataSheet1.Cells.Range["A" + row].Value2 = data.Name;
dataSheet1.Cells.Range["B" + row].Value2 = data.Value;
row++;
}
series2.XValues = "'Sheet1'!$A$2:$A$" + row;
series2.Values = "'Sheet1'!$C$2:$C$" + row;
Related
I try to put data into DataGridView and have one column for display a "link" but it create columns from amount of "link data"
ArrayList row = new ArrayList();
foreach (S3Object entry in response.S3Objects)
{
row = new ArrayList();
row.Add(Path.GetFileName(entry.Key.ToString()));
row.Add((double)entry.Size / 1024 / 1024 + " MB");
row.Add(entry.LastModified);
row.Add(entry.Owner.DisplayName);
DTGfilenames.Rows.Add(row.ToArray());
DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn();
dgvLink.UseColumnTextForLinkValue = true;
dgvLink.LinkBehavior = LinkBehavior.SystemDefault;
dgvLink.HeaderText = "Preview";
dgvLink.Name = "URLHERE";
dgvLink.LinkColor = Color.Blue;
dgvLink.TrackVisitedState = true;
dgvLink.Text = "URLHERE";
dgvLink.UseColumnTextForLinkValue = true;
Console.WriteLine(dgvLink.Name + " " + dgvLink.Text);
DTGfilenames.Columns.Add(dgvLink);
}
Its creates new column because of DTGfilenames.Columns.Add(dgvLink); inside the foreach loop.
If there is 10 items in array it will loop 10x and create column link 10x.
But you can try to remove DataGridViewLinkColumn dgvLink = new DataGridViewLinkColumn(); inside the loop and paste it before the loop
I have a DataGridView which i am populating as shown below.This DataGridView has 7 columns, where 1st, 4th & 6th columns respectively would be unbound and the rest would be bound columns.Now my requirement is
1] In column[0], i want to show an autoincrement integer value like "Serial No." 1,2,3.....n
2] At column[4], i want to show an icon/image from an imagelist.
3] At column[6], i want to show a Button control
try
{
using (FbConnection conLLV = new FbConnection(connectionString))
{
conLLV.Open();
using (FbCommand cmdLLV = new FbCommand(sqlQryLLV, conLLV))
{
cmdLLV.Parameters.Add("#t_id", FbDbType.Integer).Value = tid;
cmdLLV.Parameters.Add("#mem_id", FbDbType.Integer).Value = mid;
cmdLLV.CommandType = CommandType.Text;
using (FbDataAdapter daLLV = new FbDataAdapter(cmdLLV))
{
using (DataTable dtLLV = new DataTable())
{
daLLV.Fill(dtLLV);
dgSSW.AutoGenerateColumns = false;
dgSSW.ColumnCount = 7;
//At Column[0] ->a Serial No column
dgSSW.Columns[1].Name = "subsec_name";
dgSSW.Columns[1].HeaderText = "Sub Section Name";
dgSSW.Columns[1].DataPropertyName = "subsec_name";
dgSSW.Columns[2].Name = "rt_correct_ans";
dgSSW.Columns[2].HeaderText = "Correct Answer";
dgSSW.Columns[2].DataPropertyName = "rt_correct_ans";
dgSSW.Columns[3].Name = "rt_your_ans";
dgSSW.Columns[3].HeaderText = "Your Answer";
dgSSW.Columns[3].DataPropertyName = "rt_your_ans";
//At Column[4] ->an Image column
dgSSW.Columns[5].Name = "q_r_difficulty";
dgSSW.Columns[5].HeaderText = "Difficulty Level";
dgSSW.Columns[5].DataPropertyName = "q_r_difficulty";
//At Column[6] ->a column having a Button control
dgSSW.DataSource = dtLLV;
}//data table closed and disposed here
}// data adapter closed and disposed up here
}// command disposed here
}//connection closed and disposed here
}
catch (FbException ex)
{
MessageBox.Show("LLV--" + ex.Message);
}
How can i achieve my requirements please advise using codes.I have searched the internet but the solutions given does not match my requirements.
possible solution by steps:
0] set datasource
dgSSW.DataSource = dtLLV;
1] row numbers: add column for them and apply cell formatting
var col0 = new DataGridViewTextBoxColumn
{
HeaderText = "#", Name="RowNum",
ReadOnly = true,
Width = 10
};
dgSSW.Columns.Insert(0, col0);
dgSSW.CellFormatting += GridCellFormatting;
private void GridCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dgSSW.Columns[e.ColumnIndex].Name == "RowNum")
{
e.Value = (e.RowIndex + 1).ToString();
}
}
2] image column:
var col3 = new DataGridViewImageColumn { HeaderText = "Pic", Name = "Pic" };
dgSSW.Columns.Insert(4, col3);
// set image for a cell
dgSSW["Pic", 0].Value = Resources.add;
3] buttons column with clicks handling
var col7 = new DataGridViewButtonColumn
{
HeaderText = "Proceed", Name = "Action",
Text = "+",
UseColumnTextForButtonValue = true
};
dgSSW.Columns.Add(col7);
dgSSW.CellContentClick += GridCellContentClick;
private void GridCellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (dgSSW.Columns[e.ColumnIndex].Name == "Action")
{
MessageBox.Show((e.RowIndex + 1).ToString());
}
}
update: since you don't use AutoGenerateColumns and create all columns manually, you can create all col0, col3, col7 and after that set DataSource
I am using OpenXml to create Excel file and export table data. One of the scenario is I want a column to have dropdown of predefined values, say like true and false. I followed this question and wrote code as below
DataValidation dataValidation = new DataValidation
{
Type = DataValidationValues.List,
AllowBlank = true,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
//Formula1 = new Formula1("'SheetName'!$A$1:$A$3") // this was used in mentioned question
Formula1 = new Formula1("True,False") // I need predefined values.
};
DataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet
if (dvs != null)
{
dvs.Count = dvs.Count + 1;
dvs.Append(dataValidation);
}
else
{
DataValidations newDVs = new DataValidations();
newDVs.Append(dataValidation);
newDVs.Count = 1;
worksheet.Append(newDVs);
}
If I use it with SheetName with cell values range, it works fine, but if I add string, it throws me error "Unreadable content found" and removes datavalidation node.
How to add values for list dropdown validation in formula itself. XML it creates for manually added(by editing in excel application) list values is <formula1>"One,Two"</formula1> (observed xml for excel file)
Okay I got this solved. Added escaped double quotes to formula and done.
DataValidation dataValidation = new DataValidation
{
Type = DataValidationValues.List,
AllowBlank = true,
SequenceOfReferences = new ListValue<StringValue>() { InnerText = "B1" },
Formula1 = new Formula1("\"True,False\"") // escape double quotes, this is what I was missing
};
DataValidations dvs = worksheet.GetFirstChild<DataValidations>(); //worksheet type => Worksheet
if (dvs != null)
{
dvs.Count = dvs.Count + 1;
dvs.Append(dataValidation);
}
else
{
DataValidations newDVs = new DataValidations();
newDVs.Append(dataValidation);
newDVs.Count = 1;
worksheet.Append(newDVs);
}
I am currently using lucene.net to search the content of files for keyword search. I am able to get the results correctly but I have a scenario where I need to display the keywords found in a particular file.
There are two different files containing "karthik" and "steven", and if I search for "karthik and steven" I am able to get both the files displayed. If I search only for "karthik" and "steven" separately, only the respective files are getting displayed.
When I search for "karthik and steven" simultaneously I get both the files in the result as I am displaying the filename alone, and now I need to display the particular keyword found in that particular file as a record in the listview.
Public bool StartSearch()
{
bool bResult = false;
Searcher objSearcher = new IndexSearcher(mstrIndexLocation);
Analyzer objAnalyzer = new StandardAnalyzer();
try
{
//Perform Search
DateTime dteStart = DateTime.Now;
Query objQuery = QueryParser.Parse(mstrSearchFor, "contents", objAnalyzer);
Hits objHits = objSearcher.Search(objQuery, objFilter);
DateTime dteEnd = DateTime.Now;
mlngTotalTime = (Date.GetTime(dteEnd) - Date.GetTime(dteStart));
mlngNumHitsFound = objHits.Length();
//GeneratePreviewText(objQuery, mstrSearchFor,objHits);
//Generate results - convert to XML
mstrResultsXML = "";
if (mlngNumHitsFound > 0)
{
mstrResultsXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><Results>";
//Loop through results
for (int i = 0; i < objHits.Length(); i++)
{
try
{
//Get the next result
Document objDocument = objHits.Doc(i);
//Extract the data
string strPath = objDocument.Get("path");
string strFileName = objDocument.Get("name");
if (strPath == null) { strPath = ""; }
string strLastWrite = objDocument.Get("last_write_time");
if (strLastWrite == null)
strLastWrite = "unavailable";
else
{
strLastWrite = DateField.StringToDate(strLastWrite).ToShortDateString();
}
double dblScore = objHits.Score(i) * 100;
string strScore = String.Format("{0:00.00}", dblScore);
//Add results as an XML row
mstrResultsXML += "<Row>";
//mstrResultsXML += "<Sequence>" + (i + 1).ToString() + "</Sequence>";
mstrResultsXML += "<Path>" + strPath + "</Path>";
mstrResultsXML += "<FileName>" + strFileName + "</FileName>";
//mstrResultsXML += "<Score>" + strScore + "%" + "</Score>";
mstrResultsXML += "</Row>";
}
catch
{
break;
}
}
//Finish off XML
mstrResultsXML += "</Results>";
//Build Dataview (to bind to datagrid
DataSet objDS = new DataSet();
StringReader objSR = new StringReader(mstrResultsXML);
objDS.ReadXml(objSR);
objSR = null;
mobjResultsDataView = new DataView();
mobjResultsDataView = objDS.Tables[0].DefaultView;
}
//Finish up
objSearcher.Close();
bResult = true;
}
catch (Exception e)
{
mstrError = "Exception: " + e.Message;
}
finally
{
objSearcher = null;
objAnalyzer = null;
}
return bResult;
}
Above is the code i am using for search and the xml i am binding to the listview, now i need to tag the particular keywords found in the respective document and display it in the listview as recordsss,simlar to the below listview
No FileName KeyWord(s)Found
1 Test.Doc karthik
2 Test2.Doc steven
i hope u guys undesrtood the question,
This depends on how your documents were indexed. You'll need to extract the original content, pass it through the analyzer to get the indexed tokens, and check which matches the generated query.
Just go with the Highlighter.Net package, part of contrib, which does this and more.
string Code = "";
if (fileUp.HasFile)
{
string Path = fileUp.PostedFile.FileName;
// initialize the Excel Application class
ApplicationClass app = new ApplicationClass();
// create the workbook object by opening the excel file.
Workbook workBook = app.Workbooks.Open(Path, 0, true, 5, "", "", true,
XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
// Get The Active Worksheet Using Sheet Name Or Active Sheet
Worksheet workSheet = (Worksheet)workBook.ActiveSheet;
int index = 0;
// This row,column index should be changed as per your need.
// that is which cell in the excel you are interesting to read.
object rowIndex = 2;
object colIndex1 = 1;
object colIndex2 = 2;
object colIndex3 = 3;
object colIndex4 = 4;
object colIndex5 = 5;
object colIndex6 = 6;
object colIndex7 = 7;
try
{
while (((Range)workSheet.Cells[rowIndex, colIndex1]).Value2 != null)
{
rowIndex = 2 + index;
//string QuestionCode = (index + 1).ToString();
string QuestionCode = ((Range)workSheet.Cells[rowIndex, colIndex1]).Value2.ToString();
string QuestionText = ((Range)workSheet.Cells[rowIndex, colIndex2]).Value2.ToString();
string CorrectAnswer = ((Range)workSheet.Cells[rowIndex, colIndex3]).Value2.ToString();
string ChoiceA = ((Range)workSheet.Cells[rowIndex, colIndex4]).Value2.ToString();
string ChoiceB = ((Range)workSheet.Cells[rowIndex, colIndex5]).Value2.ToString();
string ChoiceC = ((Range)workSheet.Cells[rowIndex, colIndex6]).Value2.ToString();
string ChoiceD = ((Range)workSheet.Cells[rowIndex, colIndex7]).Value2.ToString();
// string ChoiceE = ((Excel.Range)workSheet.Cells[rowIndex, colIndex7]).Value2.ToString();
newQuestionElement = new XElement("Question");
XElement optionElement = new XElement(QuestionElement.Option);
questionType = ddlQusType.SelectedValue.ToByte();
if (!string.IsNullOrEmpty(QuestionText))
newQuestionElement.Add(new XElement(QuestionElement.QuestionText, QuestionText));
else
{
//lblMessage.Text = "Missing question in Qus No.: " + i;
break;
}
newQuestionElement.Add(new XElement(QuestionElement.QuestionType, questionType));
//newQuestionElement.Add(new XElement(QuestionElement.Randomize, chbRandomizeChoice.Checked));
newQuestionElement.Add(new XElement(QuestionElement.Answer, CorrectAnswer));
if (ChoiceA.Trim() != string.Empty)
optionElement.Add(new XElement("A", ChoiceA));
if (ChoiceB.Trim() != string.Empty)
optionElement.Add(new XElement("B", ChoiceB));
if (ChoiceC.Trim() != string.Empty)
optionElement.Add(new XElement("C", ChoiceC));
if (ChoiceD.Trim() != string.Empty)
optionElement.Add(new XElement("D", ChoiceD));
newQuestionElement.Add(optionElement);
index++;
saveData(QuestionCode.ToString());
I am using this code to retrieve the data from .xlsx file.
But if the file has any special characters in it, it is showing it as different, like so
The set S = {1,2,33……….12} is to be partitioned into three sets
A,B,C of equal size. Thus, `A U B U C = S,`
The set S = {1,2,33……….12} is to be partitioned into three sets
A,B,C of equal size. Thus, `A È B È C = S,`
Looks like an encoding issue.
I use to have this issue after reading Excel into a data table and then serializing the data table to a file.
Every time I would read the data back in from the serialized file, some symbols would be replaced with funny A's and E's.
I discovered the problem was with the encoding I was using. I then started to store excel data using Unicode encoding and have never encounter another symbol problem with Excel data again.
I hope this helps...