LinqPad customize excel export - excel

I would like to modify the export to excel function of LinqPad. I want the output to be on rows instead of columns. Example current format:
Result1
value1
value2
value3
Result2
rvalue1
rvalue2
But I want it in the following format:
Result1 Result2
value1 rvalue1
value2 rvalue2
value3

Try this one.
string Input = #"
Result1
value1
value2
value3
Result2
rvalue1
rvalue2
".Trim();
void Main()
{
var isNextColumn = true;
var theList = Input.Split('\n').Select(s => {
var anon = new { IsColumn = isNextColumn, Value = s.Trim() };
isNextColumn = string.IsNullOrWhiteSpace(s);
return anon;
}).Where(w => !string.IsNullOrWhiteSpace(w.Value)).ToList();
var table = new DataTable("Your Sheet");
theList.Where(w => w.IsColumn).ToList().ForEach(f => table.Columns.Add(f.Value));
var rowCounter = 1;
var columnName = string.Empty;
theList.ForEach(f => {
if(f.IsColumn)
{
columnName = f.Value;
rowCounter = 0;
} else {
if(table.Rows.Count <= rowCounter)
{
var newRow = table.NewRow();
newRow[columnName] = f.Value;
table.Rows.Add(newRow);
} else table.Rows[rowCounter][columnName] = f.Value;
++rowCounter;
}
});
table.Dump();
}

Related

Find a range of an object in google apps script

I am a newbie with coding and am trying to get the minimum value of a column (of a temporary sheet) and then copy that value and some data from the corresponding row to another sheet. For some reason it seems to work only once during the loop, is it because I'm trying to define a range based on an object?
function create_filter(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet1 = ss.getSheetByName("APperCountry");
const sheet2 =ss.getSheetByName("Tender");
var lanelist = sheet2.getRange(2, 1, sheet2.getLastRow(), 8).getValues();
var country = ('B:B');
var origin = ('E:E');
for(var i=2; i<=lanelist.length;i++){
Logger.log("Filter has been added.");
country = ('B'+i);
Logger.log(country);
var origin = ('E'+i)
var calc = ('M'+i);
var apname = ('N'+i);
const ori = sheet2.getRange(origin);
if(ori.isBlank()){
continue;
}
const range = sheet1.getRange("A:D");
const filter = range.createFilter();
var Ctry = sheet2.getRange(country).getValue();
const Filter_Criteria1 = SpreadsheetApp.newFilterCriteria().whenTextContains(Ctry);
const coll1 = 1;
const add_filter1 = filter.setColumnFilterCriteria(coll1,Filter_Criteria1);
const new_sheet = ss.insertSheet();
new_sheet.setName("AirportDistanceCalc");
var tempsheet = ss.getSheetByName('AirportDistanceCalc');
range.copyTo(new_sheet.getRange(1,1));
var aplist = new_sheet.getRange(2, 1, new_sheet.getLastRow()-1, 8).getValues();
new_sheet.getRange(1,5,1,1).setValue("Origin")
new_sheet.getRange(1,6,1,1).setValue("DistanceKM")
for(var j=0; j<aplist.length;j++){
Logger.log(origin);
ori.copyTo(new_sheet.getRange(j+2,5));
mainFun()
}
let comparisonRange = tempsheet.getRange("F2:F");
let comparisonRangeValues = comparisonRange.getValues().filter(String);
let minimum = comparisonRangeValues[0][0];
comparisonRangeValues.forEach((rowItem, rowIndex) => {
comparisonRangeValues[rowIndex].forEach((columnItem) => {
minimum = Math.min(minimum, columnItem);
});
});
console.log(minimum);
sheet2.getRange(calc).setValue(minimum);
tempsheet.getRange(minimum, 2).copyTo(sheet2.getRange(apname));
if (tempsheet) {
ss.deleteSheet(tempsheet);
}
filter.remove();
}
}
The minimum of a column
function mincolumn(col=1) {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet1");
const min = sh.getRange(1,col,sh.getLastRow()).getValues().flat().filter(e => !isNaN(e)).sort((a,b) => a - b)[0];
Logger.log(min);
}

Convert rows into columns with conditions

I've the following excel which needs to be transposed to columns. I have tried using the built-in formula and hte pivot table but that did not help me much since the data is in a single column and I am looking for transposing to multiple columns.
Excel: (all data in single column)
ABC1
F1
D1
Sym1
ABC2
See Link2
ABC3
F3
D3
Sym3
ABC4
See Link4
ABC5
See Link5
The output should be like:
ABC Functions Description Sym See Link
ABC1 F1 D1 Sym1
ABC2 See Link1
ABC3 F3 D3 Sym3
ABC4 See Link4
ABC5 See Link5
See that when 'See Link' is present for the row data, none of the functions, descriptions and syms are present and vice versa.
So I figured this out. Used G script in googlesheet to get this right. For anyone looking for code, here's it:
function run() {
var inputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
var outputSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Description");
var rows = new Array(new Array());
var values = inputSheet.getRange(1, 1, inputSheet.getLastRow()).getValues();
Logger.log(values.length);
var j = 0;
var endOfRow = false;
var singleRow = new Array();
for (var row in values) {
for (var col in values[row]) {
var value = values[row][col];
if(value.indexOf("F") != -1) {
singleRow[1] = value;
}
else if(value.indexOf("D") != -1) {
singleRow[2] = value;
}
else if(value.indexOf("See Link") != -1) {
singleRow[4] = value;
endOfRow = true;
}
else if(value.indexOf("Sym") != -1) {
singleRow[3] = value;
endOfRow = true;
}
else {
singleRow[0] = value;
}
}
if(endOfRow) {
rows[j] = singleRow;
j++;
endOfRow = false;
var singleRow = new Array();
}
}
for(var d=2; d < rows.length; d++) {
var singleRow = rows[d];
for(var f = 0; f < singleRow.length; f++) {
if(singleRow[f] == undefined) {
outputSheet.getRange(d, f+1).setValue("");
} else {
outputSheet.getRange(d, f+1).setValue(singleRow[f]);
}
}
}
}

Batch bills- Submission Id

I need to grab the batch bill submission id (from different vendors) of the object from netsuite.Does anyone know how to do this?
TransactionSearchBasic transSearch = new TransactionSearchBasic();
SearchResult resVendorBill = service.search(transSearch);
resVendorBill.pageSize = 25;
resVendorBill.pageSizeSpecified = true;
resVendorBill.totalRecords = SearchRecentTransCount;
resVendorBill.totalRecordsSpecified = true;
transSearch.recordType = new SearchStringField() { #operator = SearchStringFieldOperator.#is, searchValue = "vendorpayment", operatorSpecified = true };
SearchResult resVendorPayment = service.search(transSearch);
if (resVendorPayment.status.isSuccess)
{
Record[] searchPaymentRecords = resVendorPayment.recordList;
if (searchPaymentRecords != null && searchPaymentRecords.Length >= 1)
{
List<VendorPayment> lstVendorPayments = searchPaymentRecords.Select(ep => (VendorPayment)ep).OrderByDescending(epo => epo.createdDate).Take(SearchRecentTransCount).ToList();
}
}

Using Epplus to import data from an Excel file to SQL Server database table

I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

How to read values from dictionary value collection and make it comma seperated string?

I have a dictionary object as under
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>();
dictStr.Add("Culture", new List<string>() { "en-US", "fr-FR" });
dictStr.Add("Affiliate", new List<string>() { "0", "1" });
dictStr.Add("EmailAddress", new List<string>() { "sreetest#test.com", "somemail#test.com" });
And I have an entity as under
public class NewContextElements
{
public string Value { get; set; }
}
What I need to do is that for every value in a particular index of the dictionary value collection, I have to make a comma separated string and place it into List collection.
e.g. the NewContextElements collection will have (obviously at run time)
var res = new List<NewContextElements>();
res.Add(new NewContextElements { Value = "en-US" + "," + "0" + "," + "sreetest#test.com" });
res.Add(new NewContextElements { Value = "fr-FR" + "," + "1" + "," + "somemail#test.com" });
I was trying as
var len = dictStr.Values.Count;
for (int i = 0; i < len; i++)
{
var x =dictStr.Values[i];
}
no it is of-course not correct.
Help needed
Try this:
Enumerable.Range(0, len).Select( i =>
new NewContextElements {
Value = string.Join(",", dictStr.Values.Select(list => list[i]))
}
);
len is the number of items inside the individual lists (in your example, it's two).
This isn't a slick as #dasblinkenlight's solution, but it should work:
Dictionary<string, List<string>> dictStr = new Dictionary<string, List<string>>( );
dictStr.Add( "Culture", new List<string>( ) {"en-US", "fr-FR"} );
dictStr.Add( "Affiliate", new List<string>( ) {"0", "1"} );
dictStr.Add( "EmailAddress", new List<string>( ) {"sreetest#test.com", "somemail#test.com"} );
int maxValues = dictStr.Values.Select(l => l.Count).Max();
List<NewContextElements> resultValues = new List<NewContextElements>(dictStr.Keys.Count);
for (int i = 0; i < maxValues; i++) {
StringBuilder sb = new StringBuilder();
string spacer = string.Empty;
dictStr.Keys.ForEach( k => {
sb.AppendFormat( "{0}{1}", spacer, dictStr[k][i] );
spacer = ", ";
} );
resultValues.Add( new NewContextElements( ){ Value = sb.ToString() });
}
do you mean transform your data like
1 2
3 4
5 6
to
1 3 5
2 4 6
try this block of code? it can be optimized in a few ways.
var res = new List<NewContextElements>();
int i = dictStr.values.count()
for (int i=0; i < len; i++) {
NewContextElements newContextElements = new NewContextElements();
foreach (List<string> list in dictStr) {
if (newContextElements.value() == null ) {
newContextElements.value = list[i];
} else {
newContextElements.value += ", " + list[i] );
}
}
res.add(newContextElements);
}
let me know if there are problems in the code, most like there is when you write it without a real ide.

Resources