I have this Code for Reading Excell Records:
public IEnumerable<FillinEntity> Map(IEnumerable<ExcelRow> excelRows)
{
List<FillinEntity> fillinEntities = new List<FillinEntity>();
foreach (ExcelRow row in excelRows)
{
FillinEntity excell = new FillinEntity();
excell.SerialNumber = Convert.ToString(row.Cells[0]);
excell.PalletNumber = Convert.ToString(row.Cells[1]);
excell.Location = Convert.ToString(row.Cells[2]);
excell.CreatedBy = Convert.ToString(row.Cells[3]);
fillinEntities.Add(excell);
}
return fillinEntities;
}
I have this records: And it succesfully inserted
R03091294 2 2 FGROOM RYAN
My Problem: I Add column header on the excell sheet.
Serial Number Pallet Location CreatedBy -----> i need to by pass column header.
R03091294 2 2 FGROOM RYAN
Thanks in regards
You could always just skip it:
foreach (ExcelRow row in excelRows.Cast<ExcelRow>().Skip(1))
See Skip().
Note: I used Cast<ExcelRow>() in case your enumerable excelRows can't be resolved to ExcelRow.
bool is_first_row = True;
foreach (ExcelRow row in excelRows)
{
if(is_first_row)
{
is_first_row = false;
continue;
}
...
}
....
.Skip(1)
solution provided by Codesleuth is much better option.
Related
Following a tutorial, I have set up everything that needs to be set up for Google Sheets Api v4. In my Google Sheets documetnt, I have names of students in the first column, and in my second column I want to put their GPA. In my code, I made two variables that the user inputs, string name and string gpa. I want to go through column A, look for that name and insert that GPA next to it. I know I should probably use a for loop to go through the column, and compare every cell with the string the user typed, but nothing I tried so far worked.
I wrote a simple method that can get entries, for now it only prints but that can easily be changed:
static void ReadEntries()
{
var range = $"{sheet}!A1:F10";
var request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
var response = request.Execute();
var values = response.Values;
if(values != null && values.Count > 0)
{
foreach(var row in values)
{
Console.WriteLine("{0} | {1}", row[0], row[1]);
}
}
else
{
Console.WriteLine("No data found");
}
}
and a method that can update a specific cell:
static void UpdateEntry()
{
var range = $"{sheet}!B2"; //example
var valueRange = new ValueRange();
var objectList = new List<object>() { "updated" };
valueRange.Values = new List<List<object>> { objectList };
var updateRequest = service.Spreadsheets.Values.Update(valueRange, SpreadsheetId, range);
updateRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.AppendRequest.ValueInputOptionEnum.USERENTERED;
var updateResponse = updateRequest.Execute();
}
EDIT: I need help with making a for loop to go through my A column and find the student with the same name. I know how to update a cell. I just don't know how to find a cell that needs updating.
Sounds like you are very close. You already have the value you are searching in row[0] in the loop, so all you need to track the row number through your loop.
if (values != null && values.Count > 0)
{
int rowNo =0;
foreach (var row in values)
{
rowNo ++;
Console.WriteLine("{0} | {1}", row[0], row[1]);
if (row[0].ToString() == "John")
{
string rangeToUpdate = $"{sheet}!B{rowNo}:B{rowNo}";
...
}
}
}
You could also change from using a foreach to a standard for loop.
I'm not experienced in the .NET client library of the Sheets API.
However, having used the Sheets API with the node and python client libraries, I can point you to the documentation you should follow. This is the official API documentation, with code examples for each language having a Google-provided client library.
For example, here is the spreadsheets.values.update documentation that you use, with a code example for C#.
On to the question then:
According to the json representation of a ValueRange, ValueRange.Range does not seem optional even though it is redundant. You might need to add ValueRange.Range = range; in your code.
Plus, you are using SpreadsheetsResource.ValuesResource.AppendRequest instead of SpreadsheetsResource.ValuesResource.UpdateRequest in the definition of your ValueInputOption.
Let me know if it helped!
Update
This also seems to be a duplicate of Update a cell with C# and Sheets API V4
How can I iterate over an excel file?
I currently have a class using ExcelDataReader
Class => https://paste.lamlam.io/nomehogupi.cs#14fXzlopygZ27adDcXEDtQHT0tWTxoYR
I have a excel file with 5 columns
This is my current code, but it is not exporting the result that I expect ...
TextWriter stream = new StreamWriter("excel Path");
//foreach string in List<string>
foreach(var item in ComboList) {
var rows = ExcelHelper.CellValueCollection(item.Key);
foreach(var row in rows) {
stream.WriteLine(item.Key + "|" + row);
break;
}
}
stream.Close();
My result:
Column1|Row1
Column1|Row2
Column1|Row3
...
Column2|Row1
Column2|Row2
Column2|Row3
...
Expected:
Column1|Row1|Column2|Row1...
Column1|Row2|Column2|Row2...
Column1|Row3|Column2|Row3...
Thanks
This is the answer, I just needed to get the dataSet and iterate over it, very easy
var data = ExcelHelper.DataSet();
foreach (DataRow dr in data.Tables[0].Rows)
{
Console.WriteLine(dr["Column1"] + "|" + dr["Column2"]);
}
If I understand what you want truly! I think you need to add a method like RowValueCollection to your ExcelHelper as below:
public static IEnumerable<string[]> RowValueCollection()
{
var result = Data.Tables[0].Rows.OfType<DataRow>()
.Select(dr => dr.ItemArray.Select(ia => ia.ToString()).ToArray());
return result;
}
And then use it like this:
var rowValues = ExcelHelper.RowValueCollection();
foreach (var row in rowValues)
{
stream.WriteLine(string.Join("|", row));
}
HTH ;)
The first problem is that you are asking to write two items and only two items on a single line.
Would it help if you made the stream.writeline() statement into a .write() statement and then, after the inner loop performed a .writeline() which would terminate the line?
Apologies for not commenting but not enough Respect points to do so.
- Malc
I have a renderTable and I am adding rows and columns to the table as follows-
RenderTable renderTable = new RenderTable();
DataTable dt = GetData();
foreach (DataRow row in dt.Rows)
{
var header = renderTable.Rows[renderTable.Rows.Count];
header[0].Text = "Column 1";
header[1].Text = "Column 2";
header[2].Text = "Column 3";
header[1].Text = "Column 4";
var data = renderTable.Rows[renderTable.Rows.Count];
data [0].Text = row["col1"].ToString(); // 10
data [1].Text = row["col2"].ToString(); // 11
data [2].Text = row["col3"].ToString(); // 12
data [3].Text = row["col4"].ToString(); // 13
}
This is working fine and table is rendering as folllows-
Column 1 Column2 Column3 Column4
10 11 12 13
My requirement is, now I want to move the column 4 to another place like 2nd place as follows . (this place can differ depending on condition)
Column 1 Column4 Column2 Column3
10 13 11 12
I tried Insert method but it is not working for me as the insert index may change.
Is there any function of render table to move the column to specified index.
Please suggest any alternative if any.
We regret to mention but there isn't any function that can allow the moving of column of RenderTable to a specified index since the Cols of C1PrintDocument is ReadOnly.
I've done this by creating a new class from System.Web.UI.WebControls.GridView. I override CreateColumns which is used to return an array of the column objects in order. I read a cookie from the page (this allows me to change the columns via a cookie on the page) and create a new column array based on the cookie. This cookie is just a string of the column names in the order required with a | separator. I had another column picker page that would set this cookie. If you don't need to change the columns with a cookie this is not needed -- you could read / create this string from a database or configuration file. I believe the code is well commented and clear -- one note, our application has a requirement to include hidden columns, so I add those to the end of the column list before I return the array.
using System.Collections;
using System.Linq;
using System.Web.UI.WebControls;
public class ChangeColumnGridView : System.Web.UI.WebControls.GridView
{
protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
{
// Get the needful from the base class
var baseColList = base.CreateColumns(dataSource, useDataSource);
var inColList = baseColList.OfType<object>();
// Get our column order
string columnOrder;
if (Page.Request.Cookies["colOrder"] != null)
columnOrder = Page.Request.Cookies["colOrder"].Value;
else
return baseColList;
// change it to an array
string[] columnOrderA = columnOrder.Split(new char[] { '|' });
// this is where we will put our results
ArrayList newColumnList = new ArrayList();
// look for each name in the list and add when we find it.
foreach (string name in columnOrderA)
{
var found = inColList.Where((c) => c.ToString() == name).FirstOrDefault();
if (found != null)
newColumnList.Add(found);
}
// look for non-visible items in the list and add them if we don't already have them.
foreach (var a in inColList)
{
if (((System.Web.UI.WebControls.DataControlField)a).Visible == false)
{
var found = newColumnList.Cast<object>().Where((c) => c.ToString() == a.ToString()).FirstOrDefault();
if (found == null)
newColumnList.Add(a);
}
}
return newColumnList;
}
}
When I use the below line It reads all tables of that particular document:
foreach (Microsoft.Office.Interop.Word.Table tableContent in document.Tables)
But I want to read tables of a particular content for example from one identifier to another identifier.
Identifier can be in the form of [SRS oraganisation_123] to another identifier [SRS Oraganisation_456]
I want to read the tables only in between the above mentioned identifiers.
Suppose 34th page contains my identifier so I want read all tables from that point to until I come across my second identifier. I don't want to read remaining tables.
Please ask me for any clarification in the question.
Say start and end Identifiers are stored in variables called myStartIdentifier and myEndIdentifier -
Range myRange = doc.Range();
int iTagStartIdx = 0;
int iTagEndIdx = 0;
if (myRange.Find.Execute(myStartIdentifier))
iTagStartIdx = myRange.Start;
myRange = doc.Range();
if (myRange.Find.Execute(myEndIdentifier))
iTagEndIdx = myRange.Start;
foreach (Table tbl in doc.Range(iTagStartIdx,iTagEndIdx).Tables)
{
// Your code goes here
}
Not sure how your program is structured... but if you can access the identifier in tableContent then you should be able to write a LINQ query.
var identifiers = new List<string>();
identifiers.Add("myIdentifier");
var tablesWithOnlyTheIdentifiersIWant = document.Tables.Select(tableContent => identifiers.Contains(tableContent.Identifier)
foreach(var tableContent in tablesWithOnlyTheIdentifiersIWant)
{
//Do something
}
Go through following code, if it helps you.
System.Data.DataTable dt = new System.Data.DataTable();
foreach (Microsoft.Office.Interop.Word.Cell c in r.Cells)
{
if(c.Range.Text=="Content you want to compare")
dt.Columns.Add(c.Range.Text);
}
foreach (Microsoft.Office.Interop.Word.Row row in newTable.Rows)
{
System.Data.DataRow dr = dt.NewRow();
int i = 0;
foreach (Cell cell in row.Cells)
{
if (!string.IsNullOrEmpty(cell.Range.Text)&&(cell.Range.Text=="Text you want to compare with"))
{
dr[i] = cell.Range.Text;
}
}
dt.Rows.Add(dr);
i++;
}
Go through following linked 3rd number answer.
Replace bookmark text in Word file using Open XML SDK
I want to update column B to 1 for the row where the value of column A is 2. In SQL terms, a simple
UPDATE SpreadSheet
SET B = 1
WHERE A = 2
Can this be done in a one or two calls to Google Docs without having to loop over rows/columns?
I wasn't able to use B or A and couldn't find a way to do the update without looping. This example uses the column header (the value of the first row). Replace id and val with your own columns.
WorksheetFeed wsFeed = spreadsheet.Worksheets;
WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0];
// Define the URL to request the list feed of the worksheet.
AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
// Fetch the list feed of the worksheet.
ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
listQuery.SpreadsheetQuery = "id = 2";
ListFeed listFeed = service.Query(listQuery);
var row = (ListEntry)listFeed.Entries[0];
foreach (ListEntry.Custom element in row.Elements)
{
if (element.LocalName == "val")
{
element.Value = "1";
}
}
row.Update();