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.
I am using Epplus to copy a worksheet from a wokbook and paste it in another workbook.I can able to copy the worksheet sucesssfully,by using the below code.
ExcelPackage masterPackage = new ExcelPackage(new FileInfo(#"C:\\Users\\350154\\Desktop\\vb workouts\\testsample.xlsx"));
ExcelPackage pckg = new ExcelPackage(new FileInfo("C:\\Users\\350154\\Desktop\\vb workouts\\as.xlsx"));
string workSheetName = pckg.Workbook.Worksheets[1].Name;
ExcelWorksheet pck = pckg.Workbook.Worksheets[1];
pck.ConditionalFormatting.RemoveAll();
masterPackage.Workbook.Worksheets.Add(workSheetName, pck);
The code copies the sheet sucessfully.But the copied sheet has formulas in their cells.So Values not copying in a new excel pls help me to solve this.
If you're just looking to copy the values from one spreadsheet into a new sheet in another, try this:
public static void CopySheetValues(string sourcePath, string sheetName, string destPath)
{
using (var src = new ExcelPackage(new FileInfo(sourcePath)))
using (var dest = new ExcelPackage(new FileInfo(destPath)))
{
var wsSrc = src.Workbook.Worksheets[sheetName];
var wsDest = dest.Workbook.Worksheets[wsSrc.Name] ?? dest.Workbook.Worksheets.Add(wsSrc.Name);
for (var r = 1; r <= wsSrc.Dimension.Rows; r++)
{
for (var c = 1; c <= wsSrc.Dimension.Columns; c++)
{
var cellSrc = wsSrc.Cells[r, c];
var cellDest = wsDest.Cells[r, c];
// Copy value
cellDest.Value = cellSrc.Value;
// Copy cell properties
cellDest.Style.Numberformat = cellSrc.Style.Numberformat;
cellDest.Style.Font.Bold = cellSrc.Style.Font.Bold;
// TODO... Add any additional properties that you may want to copy over
}
}
dest.Save();
}
}
UPDATE: Sample code updated to show how formatting can also be copied from the source to the destination worksheet
Thanks #Pete. But I found a way to copy an entire worksheet to another workbook while I was looking for a different issue. https://github.com/JanKallman/EPPlus/issues/94
You change the below line to add the worksheet to the workbook.
var wsDest = m_GeneratedHeader.Workbook.Worksheets[wsSrc.Name] ?? m_GeneratedHeader.Workbook.Worksheets.Add(wsSrc.Name, wsSrc);
No need to use the two 'for' loops to iterate through rows and columns to copy each property. Adding the worksheet will copy cell style, font style, merge cells, etc... Worked for me.
Note that this was introduced after EPPlus 4.5.0.1
I have been stuck with this problem for a while and cannot seem to find a way around it. I have read numerous articles on Stack Overflow yet nothing seems to answer my question. The tutorials I have followed as well all give different solutions but none seem to work.
I am trying to write data from a DataTable into an excel spreadsheet. I am using Microsoft.Office.Interop.Excel package and I do have Excel installed on my pc with admin rights.
At the top of my console app I have the following:
using Microsoft.Office.Interop.Excel;
I am using the following code to create the excel spreadsheet and populate it where dt is the DataTable:
var excel = new Application();
excel.Visible = false;
excel.DisplayAlerts = false;
var workBook = (Workbook)excel.Workbooks.Add(Type.Missing);
var workSheet = (Worksheet)workBook.ActiveSheet;
workSheet.Name = "Transformed Table";
for(int row = 0; row < dt.Rows.Count; row++)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
workSheet.Cells[row + 2, i + 1] = dt.Rows[row][i].ToString();
}
}
workBook.SaveAs("C:\\Users\\******\\Downloads\\test-file.xlsx");
workBook.Close();
excel.Quit();
The end result is an empty sheet.
Based on on the suggestions in this post: How to export DataTable to Excel I was able to use the following code to generate a csv file that did what I needed:
var dtLines = new List<string>();
string[] columnNames = dt.Columns
.Cast<DataColumn>()
.Select(column => column.ColumnName)
.ToArray();
var header = string.Join(",", columnNames.Select(name => $"\"{name}\""));
dtLines.Add(header);
var valueLines = dt.AsEnumerable()
.Select(row => string.Join(",", row.ItemArray.Select(val => $"\"{val}\"")));
dtLines.AddRange(valueLines);
File.WriteAllLines("excel.csv", dtLines);
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'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.