I am working on a little project where the program takes data from a basic Excel Workbook and outputs it into a Console Application. I am currently working on trying to format the output neatly so it does not look like it is all over the place. In the examples below, The first image is the current output and the second is what I would like the output to look like.
First Output example (Current):
What I'd like it to be formatted like (Anticipated):
Here is the current code I have:
class Program
{
static void Main(string[] args)
{
string nfile = System.IO.Directory.GetCurrentDirectory() + "/Assets.xlsx";
Program p = new Program();
p.loadDB(@nfile);
}
private void loadDB(string file)
{
Application excelApp = new Application();
if (!System.IO.File.Exists(file))
{
Console.WriteLine("File does not exist");
return;
}
if (excelApp == null)
{
Console.WriteLine("Excel is not installed");
return;
}
Workbook excelBook = excelApp.Workbooks.Open(file);
_Worksheet excelSheet = excelBook.Sheets[1];
Range excelRange = excelSheet.UsedRange;
int rowCount = excelRange.Rows.Count;
int colCount = excelRange.Columns.Count;
for (int i = 1; i <= rowCount; i++)
{
Console.Write("\r\n");
for (int j = 1; j <= colCount; j++)
{
var val = (Microsoft.Office.Interop.Excel.Range)excelRange.Cells[i, j];
if (val != null && val.Value2 != null) {
Console.Write(String.Format("|{0, -5}", val.Value2 + "\t"));
}
}
}
excelApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
Console.ReadLine();
}
}
The main issue I am trying to figure out is how to use a String.Format type method or another suggestion to neatly format the data output in the console. I have tried using different methods of arrays and forloops all which have failed. This is more of a learning project than anything. If I could get an explanation and point me in the right direction, I would greatly appreciate it.