How to get Excel Columns Range in Epplus and set its Column Width? - epplus

Example. How in Epplus?
Sheet.Cells["a1:d1"].Column.Width = 10;
In Excel Interop:
Sheet.get_Range("a1", "d1").ColumnWidth = 10;

You can set the widths but have to do it per column. You can do it over a range like this:
for (int c = 1; c <= ws.Cells["A1:D1"].Columns; c++)
ws.Column(c).Width = 10;
If you want to do it on ALL cells with data you can omit the range and Epplus will only return cells with actual data in it:
for (int c = 1; c <= ws.Cells.Columns; c++)
ws.Column(c).Width = 10;

And this to start in specific Column. Not Using ws.Cells[range]
int startColumn = 3; int endColumn = 10;
for (int a = startColumn; a <= endColumn; a++)
{
Sheet.Column(a).Width = 10;
}

Related

Time complexity from pseudocode

I am trying to find the Time complexity from the lines of code. However, I am not really getting it.
int codeMT(int n) {
int a = 1;
int i = 1;
while (i < n * n) {
j = 1;
while (j < n * n * n) {
j = j * 3;
a = a + j + i;
}
i = i + 2;
}
return a;
}
In this case, this is my thought process.
Firstly, we need to start from the inner loop.
while (j < n * n * n) {
j = j * 3;
a = a + j + i;
}
In here, there is j = j * 3 which makes this log(n)(log base 3) but then we have a loop guard that has nnn which makes the n^3. Therefore, this part of code has log(n^3) time complexity.
Secondly, the outer while loop has the loop guard of n * n which makes it n^2.
Thus, O(n^2(log(n^3))
Is my approach okay? or is there anything that I am missing/things that I could improve my thought process?
Thank you

Converting Random Pairing Function from VBA to GAS

I've been working to create a random pairing algorithm for my bass club. The idea is to pair a value in Column A (Boaters) with a value in Column B (non-boaters). If there are no more non-boaters, any remaining boaters should be paired unless only one unpaired boater remains.
I found some VBA code online, which works fine in Excel, but all of my club's stuff is in Google Sheets and I'd like to have the same pairing function in GAS.
I've tried my best to convert the VBA code to GAS, but honestly, I have some experience with VBA and I'm still a relative novice at GAS, although I'm learning.
I've pasted the two VBA functions below, followed by the GAS conversion I've been working on. The comments show the areas where I'm having trouble, particularly with the called sorting function (vSortM), although I'd welcome a second set of eyes to make sure I haven't incorrectly coded something else.
Can anyone advise if I am performing the conversion from VBA to GAS correctly?
Pairing Algorithm in VBA that I found online:
Option Explicit
Sub test()
Dim Boters(), NonBoters(), i As Long, x As Long
Boters = Range("a1", Range("a" & Rows.Count).End(xlUp)).Value
Redim Preserve Boters(1 To UBound(Boters), 1 To 2)
NonBoters = Range("b1", Range("b" & Rows.Count).End(xlUp)).Value
Redim Preserve NonBoters(1 To UBound(NonBoters), 1 To 2)
Randomize
For i = 1 To UBound(Boters)
Boters(i, 2) = Rnd
Next
For i = 1 To UBound(NonBoters)
NonBoters(i, 2) = Rnd
Next
VSortM Boters, 1, UBound(Boters), 2
VSortM NonBoters, 1, UBound(NonBoters), 2
x = Application.Min(UBound(Boters), UBound(NonBoters))
With Cells(1, 4).Resize(x, 2)
.CurrentRegion.ClearContents
.Columns(1).Value = Boters
.Columns(2).Value = NonBoters
End With
If x < UBound(Boters) Then
For i = x + 1 To UBound(Boters) Step 2
If i + 1 > UBound(Boters) Then Exit For
Cells(i, 4).Value = Boters(i, 1)
Cells(i, 5).Value = Boters(i + 1, 1)
Next
End If
End Sub
Private Sub VSortM(ary, LB, UB, ref)
Dim M As Variant, i As Long, ii As Long, iii As Long, temp
i = UB: ii = LB
M = ary(Int((LB + UB) / 2), ref)
Do While ii <= i
Do While ary(ii, ref) < M
ii = ii + 1
Loop
Do While ary(i, ref) > M
i = i - 1
Loop
If ii <= i Then
For iii = LBound(ary, 2) To UBound(ary, 2)
temp = ary(ii, iii)
ary(ii, iii) = ary(i, iii): ary(i, iii) = temp
Next
ii = ii + 1: i = i - 1
End If
Loop
If LB < i Then VSortM ary, LB, i, ref
If ii < UB Then VSortM ary, ii, UB, ref
End Sub
My attempt at converting the Pairing Algorithm in GAS
function test() {
//Get values for Column A and Column B starting at Row 5
var ssMatch = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Pairings');
var bRange = ssMatch.getRange("A5:A").getValues();
var nBRange = ssMatch.getRange("B5:B").getValues();
//Determine length with data to exclude blansk
var bLast = bRange.filter(String).length;
var nBLast = nBRange.filter(String).length;
//Get values for boaters & nBoaters without blanks
var boaters = ssMatch.getRange(5,1,bLast).getValues();
var nBoaters = ssMatch.getRange(5,2,nBLast).getValues();
// Populate boaters & nBoaters arrays using random numbers
for (var i = 0; i < bLast; i++) {
boaters[i][1] = Math.random();
Logger.log(boaters);
}
for (var j = 0; j<nBLast; j++) {
nBoaters[j][1] = Math.random();
Logger.log(nBoaters);
}
vSortM (boaters, 1, bLast, 1);
vSortM (nBoaters, 1, nBLast, 1);
//Determine whether there are more boaters or non-boaters
var x = Min(bLast, nBLast);
//Write boater & nBoater values in Columns
//NEED SOME HELP HERE: Certain this isn't correct for GAS
Cells(1,4).Resize(x, 2);
Cells.CurrentRegion.ClearContents;
Cells.Columns(1).setValues(boaters);
Cells.Columns(2).setValues(nBoaters);
//If no more nBoaters, pair remaining unpaired boaters
if (x < bLast) {
for (var i = x + 1; i<bLast; i = i + 2) {
if (i + 1 > bLast) { break;}
else {
//THINK I DID THIS RIGHT, BUT NOT SURE
ssMatch.getRange(i,4).setValue(boaters[i][0]);
ssMatch.getRange(i,5).setValue(boaters[i+1][0]);
}
}
}
}
//Having some trouble converting this from VBA to GAS
// not sure how to deal with the ary parameter and m statement
function vSortM(ary, lB, uB, ref) {
var temp = 0;
var i = uB;
var ii = lB;
var m = [parseInt((lB + uB) / 2), ref];
while (ii <= i);{
while ([ii, ref] < m); {
ii++;
while ([i, ref] > m); {
i--;
}
if (ii <= i); {
for (var iii = 0; i<=(ary, 2);) {
temp = [ii, iii];
[ii, iii] = [i, iii];
[i, iii] = temp;
}
ii++;
i--;
}
}
if (lB < i) {
vSortM(ary, lB, i, ref);
}
if (ii < uB) {
vSortM(ary, ii, uB, ref);
}
}
}
First off, I have to agree with the others in the comments. The question is too broad. In https://stackoverflow.com/help/dont-ask it says that questions should be reasonably scoped.
From what I see in your code that you ask for help.
//NEED SOME HELP HERE: Certain this isn't correct for GAS
Cells(1,4).Resize(x, 2);
Cells.CurrentRegion.ClearContents;
Cells.Columns(1).setValues(boaters);
Cells.Columns(2).setValues(nBoaters);
This section is easy to figure out by using the very well written documentation for GAS (always refer to it first before going anywhere else). In GAS you are essentially working with classes (or objects if you will). Here you will want the sheet class to resize the row and column (2 seperate functions) and then a range class (which is retrieved from the sheet class) to clear and set values.
//THINK I DID THIS RIGHT, BUT NOT SURE
ssMatch.getRange(i,4).setValue(boaters[i][0]);
ssMatch.getRange(i,5).setValue(boaters[i+1][0]);
Depends on what you want to accomplish. The syntax here is correct, you set a value for a single cell. Keep in mind that in google sheets it's best to try and batch such calls. So instead of setting a value on a cell by cell basis, you would get a range from A1 to B20 and set all values at once with a 2D array.
Finally you need to clarify what it is the second functions has to do and what it doesn't do right. Perhaps share a minimal example sheet (read here about Minimal, Complete, and Verifiable example)?

Cannot find column 25 Exception coming

I am creating one report where data exported from my access database to excel here. I'm not using any datagridview , when user click one checkbox appropriate report he can able to download for this I have written code but when I run this code its giving me Cannot find column 25, I don't know why its showing me this?
In access table I have total 25 column :
string sql = null;
string data = null;
int i = 0;
int j = 0;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlWorkBook = xlApp.Workbooks.Add(misValue);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
string connectionString = null;
connectionString = ConfigurationManager.ConnectionStrings["AccessConnectionString"].ConnectionString;
cnn.ConnectionString = connectionString;
cnn.Open();
sql = "SELECT * FROM Billing WHERE Bill_No and Bill_Date is null order by FormNo desc";
OleDbDataAdapter dscmd = new OleDbDataAdapter(sql, cnn);
DataSet ds = new DataSet();
dscmd.Fill(ds);
cnn.Close();
for (j = 0; i < ds.Tables[0].Columns.Count; j++)
{
xlWorkSheet.Cells[1, j + 1] = ds.Tables[0].Columns[j].Caption; // Exception coming this line
}
for (i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (j = 0; j < ds.Tables[0].Columns.Count; j++)
{
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}
System.Windows.Forms.SaveFileDialog saveDlg = new System.Windows.Forms.SaveFileDialog();
saveDlg.InitialDirectory = #"C:\";
saveDlg.Filter = "Excel files (*.xls)|*.xls";
saveDlg.FilterIndex = 0;
saveDlg.RestoreDirectory = true;
saveDlg.Title = "Export Excel File To";
xlWorkBook.Close(true, misValue, misValue);
MessageBox.Show("File Downloaded successfully...");
xlApp.Quit();
}
i got the answer here i change my for loop
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
{
xlWorkSheet.Cells[1, j + 1] = ds.Tables[0].Columns[j].Caption;
data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
xlWorkSheet.Cells[i + 2, j + 1] = data;
}
}

Why wrong datetime order in Zedgraph

I have the following code to plot value
StockPointList spl = new StockPointList();
for (int i = 0; i < dtTable.Rows.Count; i++)
{
dtDate = Convert.ToDateTime(dtTable.Rows[i]["DateTime"]);
XDate xDate = new XDate(dtDate.Year, dtDate.Month, dtDate.Day, dtDate.Hour, dtDate.Minute, dtDate.Second);
double x = xDate.XLDate;
double open = Convert.ToDouble(dtTable.Rows[i]["BarOpen"]);
double close = Convert.ToDouble(dtTable.Rows[i]["BarClose"]);
double hi = Convert.ToDouble(dtTable.Rows[i]["BarHigh"]);
double low = Convert.ToDouble(dtTable.Rows[i]["BarLow"]);
StockPt pt = new StockPt(x, hi, low, open, close, 100000);
pt.ColorValue = close > prevClose ? 2 : 1;
spl.Add(pt);
prevClose = close;
open = close;
}
myPane.XAxis.Type = AxisType.DateAsOrdinal;
myPane.XAxis.Scale.Format = "MM/dd/yyyy\nHH:MM:ss";
The column type of "DateTime" in the datatable is of "DateTime" format. I have also used a dataview to sort "DateTime" column.
When I plot to ZedGraph, its getting plotted in correct datetime order but the values that are plotted in the X-axis is in wrong order.
Any idea to resolve this?

Project Eulers problem 16 in visual basic. Sum of digits in the number 2^1000

Project Euler's problem 16:
2^(15) = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 2^(1000)?
I have been trying to do this problem for a few days now and i just can't figure out how to get vb.net 2008 to recognize anywhere near that large a number. I have seen in other posts that some software like java has the integer type BigNumber or BigInteger but i cant find anything like that in visual basic. I'm running into this problem a lot using Visual Basic. I also can't seem to find any of the standard upper level math features in visual basic such as factorials and a few others that i can't remember but couldn't find under the math feature. any suggestions? (Sorry let me rephrase, any suggestions on how to do this stuff without switching to a different programming language.)
here's the function I wrote, it's not so difficult to do your own implementation of a BigInteger purely for this purpose (very difficult to make it efficient and versatile however, but that's what libraries are for)
Public Shared Function Problem16(ByVal power As Integer) As String
Dim digits As Integer = CInt(Int(power * Log10(2)))
Dim number(digits) As Byte
number(digits) = 1
For i As Integer = 1 To power
Dim carry As Byte = 0
For j As Integer = digits To 0 Step -1
number(j) <<= 1
number(j) += carry
If number(j) > 9 Then
carry = number(j) \ CByte(10)
number(j) -= CByte(10)
Else
carry = 0
End If
Next
Next
Dim result As Integer
For i As Integer = 0 To digits
result += number(i)
Next
Return result.ToString
End Function
There are several BigInteger libraries that are freely available which you can use.
http://msdn.microsoft.com/en-us/magazine/cc163696.aspx
http://www.codeproject.com/KB/cs/biginteger.aspx?df=100&forumid=4524&exp=0&fr=26
In this case the limitations are not necessarily the language. Visual Basic, outside of basic math operations, largely depends on the BCL for functionality. This is true of most languages which run on the CLR (including C#). In most cases though, there are libraries available which you can use to augment the functionality of the framework.
I haven't tried it but there seems to be a Big Integer construct for Visual Basic.
public static void main(String[] args) {
int m = 2, ci = 1, n = 1000, i;
int[] arr = new int[n + 1];
arr[1] = 1;
for (i = 1; i <= n; i++) {
int carry = 0;
for (int j = 1; j <= ci; j++) {
arr[j] = arr[j] * m + carry;
carry = arr[j] / 10;
arr[j] = arr[j] % 10;
}
if (carry > 0) {
while (carry > 0) {
ci++;
arr[ci] = carry % 10;
carry = carry / 10;
}
}
}
int sum = 0;
System.out.println(ci + "\n \n ");
for (int j = ci; j > 0; j--) {
System.out.print(arr[j]);
sum = sum + arr[j];
}
System.out.println("\n \n " + sum);
}
Answer:
Number of digits in 2^1000: 302
2^1000=
10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376
sum of the digits: 1366