Coder Social home page Coder Social logo

consoletables's Introduction

ConsoleTable

Have you ever just wanted to output flat structured POCO out to console? Sure you have! This class will let you print a nicely formatted table right to your console as easily as possible.

Example usage

// using ConsoleTables;
static void Main(String[] args)
{
    var table = new ConsoleTable("one", "two", "three");
    table.AddRow(1, 2, 3)
         .AddRow("this line should be longer", "yes it is", "oh");

    table.Write();
    Console.WriteLine();

    var rows = Enumerable.Repeat(new Something(), 10);

    ConsoleTable
        .From<Something>(rows)
        .Configure(o => o.NumberAlignment = Alignment.Right)
        .Write(Format.Alternative);

    Console.ReadKey();
}

Console output

FORMAT: Default:

 --------------------------------------------------
 | one                        | two       | three |
 --------------------------------------------------
 | 1                          | 2         | 3     |
 --------------------------------------------------
 | this line should be longer | yes it is | oh    |
 --------------------------------------------------

 Count: 2


FORMAT: Alternative:

+----------------------------+-----------+-------+
| one                        | two       | three |
+----------------------------+-----------+-------+
| 1                          | 2         | 3     |
+----------------------------+-----------+-------+
| this line should be longer | yes it is | oh    |
+----------------------------+-----------+-------+

FORMAT: Minimal:

one                         two        three
--------------------------------------------
1                           2          3
this line should be longer  yes it is  oh

Sample Output (Screenshot)

screenshot

Adding it to your project with nuget

Package Manager

Install-Package ConsoleTables -Version 2.4.2

.NET CLI

dotnet add package ConsoleTables --version 2.4.2

PackageReference

<PackageReference Include="ConsoleTables" Version="2.4.2" />

Packet CLI

paket add ConsoleTables --version 2.4.2

Version History

Version Downloads Last updated
Version Downloads Last updated
2.4.2 18,202 4 months ago
2.4.1 42,442 7 months ago
2.4.0 19,443 12/18/2019
2.3.0 107,954 3/20/2019
2.2.4 678 3/6/2019

The MIT License (MIT)

Copyright (c) 2013 Khalid Abuhakmeh

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

consoletables's People

Contributors

ad313 avatar alexandre-machado avatar chuongmep avatar dahlsrud avatar doron-nathan-epstein avatar gsmander avatar jonfuller avatar jtone123 avatar khalidabuhakmeh avatar lumirris avatar olduh29 avatar raphaelsilv avatar seankilleen avatar spitfire05 avatar staff0rd avatar vcsjones avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

consoletables's Issues

Formatted view of Table

if somebody writes Elongated Lines in the Particular cell then it should be truncated to next line and print Like this

+====+=====+====+
| ID | Status | check |
+====+=====+====+
| 1 | Success | Trubxz|
| | | vkj;shd|
| | |kjsdah; |
| | | ;kjhdsa|
| | | kjh;kjd |
| | |kjdsa;k |
+-------+--------+--------+

Make Count Optional

Allow user's to choose whether or not to write out the total count at the bottom of the results.

This can be set as an option on the constructor or potentially on ToString.

Special Characters break column alignment

Special Characters like äöüßé break the column alignment.

Left output is expected but instead right output is produced:

Bildschirmfoto 2023-11-06 um 10 50 23

Expected Output would be

--------------  
| Name | Age |
-------------- 
| René |  59 |
-------------- 
| Otto |  52 |
-------------- 

but instead

--------------- 
| Name  | Age |
--------------- 
| René |  59 |
--------------- 
| Otto  |  52 |
--------------- 

Add scroll bar for table with many columns

when there are many columns, the table row wraps and it doesn't look good, it'd be nice if there would be a way to scroll in the console instead to the right, avoiding wrapping of contents

Box-drawing characters

It could print the table using box-drawing characters.

┌───────┬─────┐
│ Name  │ Age │  
├───────┼─────┤
│ Alice │  10 │
│ Bob   │  20 │    
│ Clare │  30 │    
└───────┴─────┘

Doco: Can you nominate formatting for particular columns(properties)?

Doco: Can you nominate formatting for particular columns(properties)? Can I get a coding example please?

For example in a column/property was say an "balance" (e.g. decimal) and I wanted to apply the formatting such as "this.Balance.ToString("c", CultureInfo.GetCultureInfo("en-AU"));".

Port To Latest .NET Core Tooling

Currently, I have the branch aspnetcore-tooling-2017 but there are a few things I'd like to be able to do.

  1. Be able to target multiple frameworks: netstandard1.2 and net40.
  2. Be able to run dotnet pack on the ConsoleTables.csproj and get all the nuget metadata right.
  3. Not pull my freaking hair out! (Optional)

** update, trying to go for netstandard1.2

Nuget please

You're amazing. Will you please publish a nuget for this?

NuGet package is missing a strong name

The NuGet package ConsoleTables is missing a strong name. I am happy to send a pull request to implement this. Please let me know if you would like that. 😄

Support nested collections

given:

    new Creator{Id = 1, FullName = @"Douglas Adams", Born = new DateOnly(1952,4,11), Died = new DateOnly(2001,5,11)};
	new Work{Id = 41, CreatorId = 1, Title = @"Young Zaphod Plays It Safe"};

Result:

	 ---------------------------------------------------------------------------------------------------------------------- 
	 | Id | FullName      | Born       | Died       | PrimaryLanguage | Works                                             |
	 ---------------------------------------------------------------------------------------------------------------------- 
	 | 1  | Douglas Adams | 04/11/1952 | 05/11/2001 |                 | System.Collections.ObjectModel.Collection`1[Work] |
	 ---------------------------------------------------------------------------------------------------------------------- 

It would be really nice if instead of System.Collections.ObjectModel.Collection1[Work]` the following table was inserted:

	 -------------------------------------------------------------------- 
	 | Id | Title                      | Language | CreatorId | Creator |
	 -------------------------------------------------------------------- 
	 | 41 | Young Zaphod Plays It Safe |          | 1         | Creator |
	 -------------------------------------------------------------------- 

Multiline

Hello

Just wondering if it is possible to use a newline within a row/column to create a multiline effect. Currently when I use \n it creates a whole new line and messes up the table format.

Thanks!

NuGet package error

Hello there, there seems to be a problem with your NuGet package.

Severity Code Description Project File Line Suppression State
Error Failed to fetch results from V2 feed at 'https://ci.appveyor.com/nuget/openssl-oaib8n7lvvtp/FindPackagesById()?id='runtime.ubuntu.16.04-x64.runtime.native.System.Security.Cryptography.OpenSsl'&semVerLevel=2.0.0' with following message : The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.

add NullFormat provider

Consider adding CustomFormatter support, plus ready to use NullFormat provider.

Code:
// add each row
var results = Rows.Select(row => string.Format(**ValuesFormatProvide**r, format, row)).ToList();

Class

	public class NullFormat : IFormatProvider, ICustomFormatter
	{
		public object GetFormat(Type service)
		{
			if (service == typeof(ICustomFormatter))
			{
				return this;
			}
			else
			{
				return null;
			}
		}

		public string Format(string format, object arg, IFormatProvider provider)
		{
			if (arg == null)
			{
				return "NULL";
			}
			IFormattable formattable = arg as IFormattable;
			if (formattable != null)
			{
				return formattable.ToString(format, provider);
			}
			return arg.ToString();
		}
	}

String.Format throws exception

On my setup (Mono/.Net 4.5), String.Format throws exception (incorrect input string format).

Seems to be caused by spaces in the alignment component

ConsoleTable.cs#69 produces those spaces (e.g. "{0, -1 }" instead of "{0,-1}"). With spaces removed, everything seems to work alright.

Add background color support

It´d be great if you could add a background color to each row based on some property of the item, that could be defined by a delegate.
For example, you add an overload that accepts a function like this

ConsoleTable.From<Item>(myResults, (item) => { item.Value > 50 ? RowBackground.Red : RowBackground.Green }).Write();

In this case rows that contain items with value bigger than 50 will be printed out with a red background, the rest with a green one.

Add simple SortBy (with code)

Hi there

I'm seeing this library and thanks for making available for all.
I suggest to add a new option to output with some Sort selected by Column index. KISS. No fuzz.

Modified to be the less intrusive possible and automatically for every output.

Usage:

Table.Options.SortByColumn = 1;  // index base zero of columns
Table.ToString(); // whatever output  due getter modification

Rows:

            private IList<object[]> _Rows { get; set; }
            public IList<object[]> Rows 
            {
                get
                {
                    if (Options.SortByColumn == -1)
                    {
                        return _Rows;
                    }
                    else if (Options.SortByColumn < Columns.Count)
                    {
                        return _Rows.OrderBy(w => (string)w[Options.SortByColumn]).ToList();
                    }
                    else
                    {
                        throw new Exception("Invalid ConsoleTable.Options.SortByColumn: " + Options.SortByColumn);
                    }
                }

                protected set
                {
                    _Rows = value;
                }
            
            }

Options:

 public class ConsoleTableOptions
    {
(,,,)
        /// <summary>
        /// Sort by Column Index  (no sort = -1 )
        /// </summary>
        public int SortByColumn { get; set; } = -1;
(...)
    }

Please check anf if you agree add it to your code.

Thanks
Ricardo

Display issue with non-English languages

If any Chinese, Japanese, emoji character appeared in the table, it won't display properly.

Steps to reproduce the problem:

add some non-English letters in the table

var table = new ConsoleTable("1", "2", "3");
table.AddRow("张三", "test", "李四");
table.AddRow("チルノ", "日本語", "😑😑😭");
table.Write();

Excepted behavior:

 -----------------------------
 | 1      | 2      | 3       |
 -----------------------------
 | 张三   | test   | 李四     |
 -----------------------------
 | チルノ | 日本語  | 😑😭😭 |
 -----------------------------

Actual behavior:

 -----------------------
 | 1   | 2    | 3      |
 -----------------------
 | 张三  | test | 李四     |
 -----------------------
 | チルノ | 日本語  | ���😑😭😭 |
 -----------------------

image

Array support for AddRow

Currently the AddRow function takes params object[] values:

public ConsoleTable AddRow(params object[] values)

And afterwards checks the length:

if (Columns.Count != values.Length)

But when we want to add a row from an array like so:

table.AddRow(new[] {1, 2, 3})

values.Length will return 1, which will result in the exception The number columns in the row (x) does not match the values (x).

It would be nice to be able to use an array like in my example so that the table can be filled more dynamically.

Table.Write() with alternative format throws null ref

Setting the format inside the constructor of table.Write to Format.Alternative, causes a null reference exception to be thrown. Happening somewhere in ToStringAlternative() method

System.NullReferenceException: Object reference not set to an instance of an object.
   at ConsoleTables.ConsoleTable.ToStringAlternative()
   at ConsoleTables.ConsoleTable.Write(Format format)

Support wrapping of contents in a fixed-width cell

It would be handy to enable the wrapping of the contents in a fixed-width cell.

+---------------------+--------------------------------------------------+
| Number              | Message                                          |
+---------------------+--------------------------------------------------+
| 4                   |  Some text wrapping itself onto the next line    |
|                     |  of this cell.                                   |
+---------------------+--------------------------------------------------+
| 12                  |  This text is not wrapping.                      |
+---------------------+--------------------------------------------------+

No updates in 2 years

I've noticed there haven't been any updates in a few years. @khalidabuhakmeh do you need help? Nuget is showing there are 700k of downloads - so there is plenty of demand!

Plz update Nuget package

Hello,
thanx for the great tool! But could you please update the nuget package to the version that is .net4.0 compatible?

Install-Package : Could not install package 'ConsoleTables 1.0.0'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly references or content files that are compatible
with that framework.

Table will went wrong if some chars' width is two. (如果某些字符的宽度是2, 表格将出错)

image
image

English:
Clearly, if a char which width is two, this current row will move right...
Also, if you want to calculate the width of a string in the console, see this repository: Null.ConsoleEx

using namspace Null.ConsoleEx, and call this method: ConsoleEx.GetStringDisplayLength(string str);

Chinese :
下面是中文:
显然, 如果一个字符的宽度是2, 当前的这一行就会向右移动...
对了, 如果你想计算字符串在控制台中的宽度, 看看这个仓库吧: Null.ConsoleEx
using Null.ConsoleEx 命名空间, 然后调用这个方法: ConsoleEx.GetStringDisplayLength(string str);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.