Heres what I have:
if (int.TryParse(kit_csv_quantity.Text, out int kitOut))
{
decimal kitOutValue = kitOut + kits_upDown.Value;
kit_csv_quantity.Text = kitOutValue.ToString();
ItemLine IL = new ItemLine();
kitOutValue = IL.Quantity;
allItems.Add(IL);
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
var workbook = ExcelFile.Load(#"C:\\Users\\carson.sumner\\Desktop\\PSP Kanban Program\\Backend Files\\Kits_be.csv", new CsvLoadOptions(CsvType.CommaDelimited));
var worksheet = workbook.Worksheets[0];
var row = worksheet.Rows[worksheet.Rows.Count];
var column = worksheet.Columns[worksheet.Columns.Count];
var searchText = kit_csv_quantity.Text;
var range = worksheet.Cells.GetSubrange("C2:C25");
row.Cells[2].Value = searchText;
workbook.Save("Output.csv", new CsvSaveOptions(CsvType.CommaDelimited));
What I have works to get the numericUpDownValue and add it into the Spreadsheet, but it just adds it into the bottom of the spreadsheet. What I want to be able to do is use the numericUpDownValue to edit a value in a pre-existing cell in the spreadsheet.
I am using gembox-spreadsheet to read the csv file into an excel workbook to edit the values, and then writes the excel worksheet back into a csv file.
So I have a list of data that I am trying to export to excel. I just want to list it going down column 1 but it refuses. I was originally going to use a foreach loop but i was worried that would slow down my program and i wouldn't be able to use the for loop idea i had. Does anyone have any good ideas to just import this. I feel like it shouldn't be as hard as i am making it. This is what i have done so far. Thanks in advance.
if (dialog == DialogResult.Yes)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)excel.ActiveSheet;
ws.Cells[1, 1] = "Folder Names";
for (int row = 0; row <= count; row++)
{
ws.Cells [1, row+2] = Namelist;
}
excel.Visible = true;
}
I want to go sequentially down the list as well. (the code above wont export Namelist, rest works though)
Namelist = list
int count (it is a counter i started earlier in the program to determine the number of lines of Namelist)
If Namelist is List<string>, the easiest way is to copy it to the Clipboard:
var text = "Folder Names\n" + string.Join("\n", Namelist); // or "\r\n"
System.Windows.Forms.Clipboard.SetText(text);
var xl = new Microsoft.Office.Interop.Excel.Application();
var wb = xl.Workbooks.Add();
var ws = xl.ActiveSheet as Worksheet;
ws.Range("A1").PasteSpecial();
xl.Visible = true;
or even easier because Excel is associated with .csv files by default:
var fileName = #"list.csv"; // or change to .xls and get warning message box
System.IO.File.WriteAllText(fileName, "Folder Names\n" + string.Join("\n", Namelist));
System.Diagnostics.Process.Start(fileName);
Update
CSV stands for Comma Separated Values, so if you want the list in a different column you have to add commas before the values. For example in columns 2 and 4:
,Folder Names,,Folder Size
,name1,,256
,name2,,"1,024"
If you have 2 lists with the same size, you can zip them together:
string[] names = {"name1", "name2"};
int[] sizes = {256, 1024};
var lines = names.Zip(sizes, (name, size) => name + "," + size); // {"name1,256", "name2,1024"}
var csv = "Names,Sizes\n" + string.Join("\n", lines);
The for loop won't slow down your program, but accessing the cells individually will. Each call to Cells is a COM-interop call, which is relatively expensive. It's much faster to put your data in an array, define a Range that represents the entire range of output, and set the Value there:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
var wbs = excel.Workbooks;
Workbook wb = wbs.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)excel.ActiveSheet;
List<object> data = new List<object>
data.Add("Folder Names");
for (int row = 0; row <= count; row++)
{
data.Add(Namelist);
}
Excel.Range rng = (Excel.Range)ws.Range[ws.Cells[1, 1], ws.Cells[1,count + 2]];
rng.Value = data.ToArray();
excel.Visible = true;
Assuming Namelist is a string[] or List<string> what you're missing is the extraction of each item from the Namelist collection before setting the value of each cell:
ws.Cells[1, 1] = #"Folder names";
for(int row = 2; row <= count; row ++)
{
var name = Namelist[row-2];
ws.Cells[1, row] = name;
}
When you use the Cells property the first argument is the row, the second is the column. You have it reversed.
Also, if you haven't gone too far down the path of learning Excel interop, I would switch to EPPlus. It's 100x times easier to work with, doesn't involve messing with COM objects, and doesn't even require Excel. It's just better.
Super easy way to export your list to excel using c#
How to install ClosedXML with NuGet Packager Manager Console:
PM> Get-Project [ProjectName] | Install-Package ClosedXML
using (var conn = new DB.Entities())
{
var stories = (from a in conn.Subscribers
orderby a.DT descending
select a).Take(100).ToList();
var ShowHeader = true;
PropertyInfo[] properties = stories.First().GetType().GetProperties();
List<string> headerNames = properties.Select(prop => prop.Name).ToList();
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Subscribers");
if (ShowHeader)
{
for (int i = 0; i < headerNames.Count; i++)
ws.Cell(1, i + 1).Value = headerNames[i];
ws.Cell(2, 1).InsertData(stories);
}
else
{
ws.Cell(1, 1).InsertData(stories);
}
wb.SaveAs(#"C:\Testing\yourExcel.xlsx");
}
I'm using SmartXLS workbook to read an excel file, I can access to the data at index like ::
var workbook = new WorkBook();
workbook.read(filePath); //read from Excel File
var dataTable = workbook.ExportDataTable(); //export to DataTable
var tenderResponseLineData = new List<TenderResponseLine>();
for (int i = 1; i < dataTable.Rows.Count; i++)
{
Code = dataTable.Rows[i].ItemArray[3].ToString().Trim(), //Get code
ProductName = dataTable.Rows[i].ItemArray[5].ToString().Trim(), //get ProductName
}
Now I want to get the cell position (column letter, position-line) of data such as L4, or B3. I don't know if SmartXLS has this function or not ? I have searched on SmartXLS site but I haven't found information about this
Thanks,
I'm using EPPlus to manipulate an Excel file. I need to insert a formula that references an entire column. I'm currently using:
currentWorksheet.Cells[2, 4].Formula = "QUARTILE(C:C,1)";
If I manually enter this formula into the Excel sheet it works, or if I insert it with a finite range in EPPlus like so:
=QUARTILE(C2:C1000,1)
But when it's inserted as a whole column range of C:C using EPPlus it results in the following:
=QUARTILE(#REF!,1)
Is there something special needed when referencing entire columns, or is this just a bug in EPPlus?
You can use following code
worksheet.Cells["A1"].Formula= "=QUARTILE(C2:C1000,1)";
Stewart is correct in that the formula should be valid. Try pasting in the rest of your code. I thought together a quick unit test and it worked fine:
[TestMethod]
public void Quartile_Range_Test()
{
//Throw in some data
var dtMain = new DataTable("tblData");
dtMain.Columns.Add(new DataColumn("Col1", typeof(int)));
for (var i = 0; i < 20; i++)
{
var row = dtMain.NewRow();
row["Col1"] = i * 100;
dtMain.Rows.Add(row);
}
//Clear the file
var newFile = new FileInfo(#"C:\Temp\Temp.xlsx");
if (newFile.Exists)
newFile.Delete();
using (var package = new ExcelPackage(newFile))
{
var currentWorksheet = package.Workbook.Worksheets.Add("Test");
currentWorksheet.Cells["C1"].LoadFromDataTable(dtMain, false);
currentWorksheet.Cells[2, 4].Formula = "QUARTILE(C:C,1)";
package.Save();
}
}
I've found how to read first line from Excel file with specific sheet name, but in my case I have to read first line of the first sheet.
How can I realize that or I have to use CSV instead of XLS?
Did you take a look at the EPPlus library? It makes very easy to work with excel files.
Here is how you would do that using EPPlus:
FileInfo existingFile = new FileInfo("yourfilepathname");
using (var package = new ExcelPackage(existingFile))
{
ExcelWorkbook workbook = package.Workbook;
if (workbook != null && workbook.Worksheets.Count > 0)
{
//Gets the first worksheet. You can use index also to select your worksheet.
ExcelWorksheet worksheet = workbook.Worksheets.First();
int rowIndex = 0;
int colIndex = 0;
//To get the first cell:
var cellValue = worksheet.Cells[rowIndex, colIndex].Value;
//YOU CAN ALSO DO A LOOP TO GET ALL VALUES FROM THE FIRST ROW.
}
}
NPOI is another good option and it can handle XLS files too.
Here's a snippet of NPOI code:
HSSFWorkbook _hssfworkbook = new HSSFWorkbook(OpenFileStream(filePath));
//Getting the sheet
_currentSheet = _hssfworkbook.GetSheetAt(0);
//Getting the row:
_row = CurrentSheet.GetRow(0);
//Getting the cell
_cell = _row.GetCell(0);
Have you considered SpreadsheetLight? Here's how you do it:
SLDocument sl = new SLDocument("YourExcelFile.xlsx", "TheSheetName");
string FirstLine = sl.GetCellValueAsString("A1");
sl.CloseWithoutSaving();
Disclaimer: I wrote SpreadsheetLight.