Tag Archives: C Course

C#: Analysis of the difference between write() and writeline()

Both write() and writeline() are methods provided by system.console, which are mainly used to display the output stream from the specified output device (screen by default).
the differences between the two methods are as follows:

The console. Writeline() method outputs the string to be output together with the newline control character. When the next statement is executed, the cursor will move to the next line of the current output string.
as for the console. Write() method, the cursor will stop after the last character of the output string in C # tutorial, and will not move to the next line.

The difference between write() and writeline()

All the methods provided by system.console
are displayed on the screen
write() does not wrap after it is displayed, and writeline() wraps
code examples

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace The difference between WriteLine and Write
WriteLine
class Program
{
static void Main(string[] args)
{
//WriteLine output with mouse at the beginning of the next line
//Write output does not start a new line
System.Console.WriteLine("First WriteLine Line");
System.Console.WriteLine("Second WriteLine Line");
 
System.Console.Write("First Write Line");//Instead of starting a new line after the First Write Line, the output is directly followed by the Second Write Line
System.Console.Write("Second Write Line");
 
//passing parameters
System.Console.WriteLine("\nWriteLine:Parameter={0}", 123);
System.Console.Write("Write:Parameter={0}", 456);
System.Console.ReadKey();
}
}
}
output

First WriteLine Line
Second WriteLine Line
First Write LineSecond Write Line
WriteLine:Parameter=123
Write:Parameter=456

Here is the article about the difference between write() and writeline() in C #. For more information about CSharp write and writeline, please search the previous articles of script home or continue to browse the following related articles. I hope you can support them in the future

Explain the performance comparison of contains, exists, any and where in C# list in detail

Test
create a new person class

public class Person
  {
    public Person(string name,int id)
    {
      Name = name;
      Id = id;
    }
    public string Name { get; set; }
    public int Id { get; set; }
 
  }

Initialize a million pieces of data in the list, and then use each method to determine whether Xiaoming is in the list. The code is as follows

static void Main(string[] args)
    {
      List<Person> persons = new List<Person>();
      //Initialize persons data
      for (int i = 0; i < 1000000; i++)
      {
        Person person = new Person("My" + i,i);
        persons.Add(person);
      }
      Person xiaoming=new Person("My999999", 999999);
       
      //The following three methods are used to determine whether persons contain xiaoming
      Stopwatch watch = new Stopwatch();
      watch.Start();
      bool a = persons.Contains(xiaoming);
      watch.Stop();
 
      Stopwatch watch1 = new Stopwatch();
      watch1.Start();
      bool b = persons.Exists(x=>x.Id==xiaoming.Id);
      watch1.Stop();
 
      Stopwatch watch2 = new Stopwatch();
      watch2.Start();
      bool c = persons.Where(x=>x.Id==xiaoming.Id).Any();
      watch2.Stop();
 
      Stopwatch watch3 = new Stopwatch();
      watch3.Start();
      bool d = persons.Any(x => x.Id == xiaoming.Id);
      watch3.Stop();
 
      Console.WriteLine("Contains time:" + watch.Elapsed.TotalMilliseconds);
      Console.WriteLine("Exists time:" + watch1.Elapsed.TotalMilliseconds);
      Console.WriteLine("Where time:" + watch2.Elapsed.TotalMilliseconds);
      Console.WriteLine("Any time:" + watch3.Elapsed.TotalMilliseconds);
      Console.ReadLine();
    }

The execution result is shown in the figure below

Conclusion
it can be seen from the figure above that the performance ranking is

Contains > Exists > Where > Any

Note:
no query conditions are allowed in contains

This article about the detailed explanation of C # list contains, exists, any, where performance comparison is introduced here. For more related C # contains, exists, any, where content, please search the previous articles of C # tutorial script home or continue to browse the following related articles. I hope you can support more in the future

Read multiple sheets of an excel file according to npoi

As we all know, npoi components can read and create Excel files when you don’t have Office installed locally. But we usually read the first sheet of C # tutorial of an excel file by default. So if you want to read all the sheets of an excel, what should you do?

Now let’s tell you how to operate npoi to read all sheets of Excel.

First of all, let’s explain how to operate a class created by Excel, which I named execlhelp

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
  
  
  public class ExcelHelper : IDisposable
        {
            private string fileName = null; //file name
            private IWorkbook workbook = null;
            private FileStream fs = null;
            private bool disposed;
  
            public ExcelHelper(string fileName)
            {
                this.fileName = fileName;
                disposed = false;
            }
  
            /// <summary>
            /// Import DataTable data into excel
            /// </summary>
            /// <param name="data">Data to be imported</param>
            /// <param name="isColumnWritten">The column name of the DataTable to import or not</param>
            /// <param name="sheetName">The name of the excel sheet to import</param>
            /// <returns>the number of rows of data to import (the row containing the column name)</returns>
            public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
            {
                int i = 0;
                int j = 0;
                int count = 0;
                ISheet sheet = null;
  
                fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                if (fileName.IndexOf(".xlsx") > 0) // v-2007
                    workbook = new XSSFWorkbook();
                else if (fileName.IndexOf(".xls") > 0) // v-2003
                    workbook = new HSSFWorkbook();
  
                try
                {
                    if (workbook != null)
                    {
                        sheet = workbook.CreateSheet(sheetName);
                    }
                    else
                    {
                        return -1;
                    }
  
                    if (isColumnWritten == true) //Write the column names to the DataTable
                    {
                        IRow row = sheet.CreateRow(0);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
                        }
                        count = 1;
                    }
                    else
                    {
                        count = 0;
                    }
  
                    for (i = 0; i < data.Rows.Count; ++i)
                    {
                        IRow row = sheet.CreateRow(count);
                        for (j = 0; j < data.Columns.Count; ++j)
                        {
                            row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
                        }
                        ++count;
                    }
                    workbook.Write(fs); //write to the excel
                    return count;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception: " + ex.Message);
                    return -1;
                }
            }
  
            /// <summary>
            /// Import data from excel to DataTable
            /// </summary>
            /// <param name="sheetName">The name of the excel workbook sheet</param>
            /// <param name="isFirstRowColumn">whether the first row is the column name of the DataTable</param>
            /// <returns>returnedDataTable</returns>
            ///
  
  
                public Dictionary<int,string> ReturnSheetList()
            {
                Dictionary<int, string> t = new Dictionary<int, string>();
                ISheet sheet = null;
                DataTable data = new DataTable();
                int startRow = 0;
                    try
                    {
                        fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        if (fileName.IndexOf(".xlsx") > 0) // 2007
                            workbook = new XSSFWorkbook(fs);
                        else if (fileName.IndexOf(".xls") > 0) // 2003
                            workbook = new HSSFWorkbook(fs);
                        int count = workbook.NumberOfSheets; //get all SheetName
                        for(int i=0;i<count;i++)
                        {
                            sheet = workbook.GetSheetAt(i);
                            if (sheet.LastRowNum > 0)
                            {
                                t.Add(i, workbook.GetSheetAt(i).SheetName);
                            }
                        }
                        return t;
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                   
  
            }<br>        ///index excel
            public DataTable ExcelToDataTable(int index)
            {
                ISheet sheet = null;
                DataTable data = new DataTable();
                int startRow = 0;
                try
                {
                    fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                    if (fileName.IndexOf(".xlsx") > 0) // 2007
                        workbook = new XSSFWorkbook(fs);
                    else if (fileName.IndexOf(".xls") > 0) // 2003
                        workbook = new HSSFWorkbook(fs);
                    //int coutnts = workbook.NumberOfSheets;
  
                    sheet = workbook.GetSheetAt(index);
                    //string names= sheet.SheetName;
                    if (sheet != null)
                    {
                        IRow firstRow = sheet.GetRow(0);
                        int cellCount = firstRow.LastCellNum; //The number of the last cell in a row is the total number of columns
  
  
                        for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                        {
                            ICell cell = firstRow.GetCell(i);
                            CellType c = cell.CellType;
                            if (cell != null)
                            {
                                string cellValue = cell.StringCellValue;
                                if (cellValue != null)
                                {
                                    DataColumn column = new DataColumn(cellValue);
                                    data.Columns.Add(column);
                                }
                            }
                        }
                        startRow = sheet.FirstRowNum + 1;
  
  
                        //The last column of the marker
                        int rowCount = sheet.LastRowNum;
                        for (int i = startRow; i <= rowCount; ++i)
                        {
                            IRow row = sheet.GetRow(i);
                            if (row == null) continue; //Rows with no data are null by default       
  
                            DataRow dataRow = data.NewRow();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) ! = null) // Similarly, cells with no data are null by default
                                    dataRow[j] = row.GetCell(j).ToString(); 
                            }
                            data.Rows.Add(dataRow);
                        }
                    }
  
                    return data;
                }
                catch (Exception ex)
                {
                    return null;
                    throw new Exception(ex.Message);
  
                }
            }
  
            public void Dispose()
            {
                Dispose(true);
                GC.SuppressFinalize(this);
            }
  
            protected virtual void Dispose(bool disposing)
            {
                if (!this.disposed)
                {
                    if (disposing)
                    {
                        if (fs != null)
                            fs.Close();
                    }
  
                    fs = null;
                    disposed = true;
                }
            }
        }<br><br>

The datatabletoexcel method is to export data to excel, and the parameters are annotated in the code, which can be applied directly. Exceltodatatable mainly imports Excel data into databtable. Similarly, parameters are also included in comments. We mainly talk about the returnsheetlist method. Before reading, we need to judge whether the imported excel version is a high version or a low version. This is because npoi provides different operation classes of high and low versions. Versions greater than 03 and less than 07 provide hssfworkbook, and versions less than 07 provide xssfworkbook. then workbook.NumberOfSheets This is mainly to get how many sheets there are in an excel file. We read the sheet according to the loop traversal, and then transfer the name of the sheet name and the corresponding index to a data dictionary for saving. So the data dictionary contains all the content sheets and corresponding indexes of the excel file you imported. With the use of exceltodatatable, you can switch to read different sheets of an excel.

The above is the details of reading multiple sheets of an excel file according to npoi

C# implementation of TXT document to table example code

code:

public DataTable TXTToDataTable(string fileName, string columnName)
    {
      DataTable dt = new DataTable();
      FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
      StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
      //Record the line read each time
      string strLine = "";
 
      //record the content of each field in each line of the record
      string[] aryLine;
      //Mark the number of columns      
      int columnCount = 0;
      //indicate whether it is the first line read
      bool IsFirst = true;
 
      if (IsFirst == true)
      {
        //strLine = "ATTENDANCE_DATE,EMP,ATTENDANCE_DEPT,EMP_TYPE,SHITF,PLANT_CODE";
        strLine = columnName;
        aryLine = strLine.Split(',');
        IsFirst = false;
        columnCount = aryLine.Length;
        //create raw
        for (int i = 0; i < columnCount; i++)
        {
          DataColumn dc = new DataColumn(aryLine[i].ToUpper());
          dt.Columns.Add(dc);
        }
      }
 
      //Read the data in txt line by line
      while ((strLine = sr.ReadLine()) != null)
      {
        aryLine = strLine.Split('\t');//tab
        DataRow dr = dt.NewRow();
        for (int j = 0; j < columnCount; j++)
        {
          dr[j] = aryLine[j].ToUpper();
        }
        dt.Rows.Add(dr);
      }
 
      sr.Close();
      fs.Close();
      return dt;
    }
public DataTable TXTToDataTable(string fileName, string columnName)
    {
      DataTable dt = new DataTable();
      FileStream fs = new FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
      StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default);
      //Record the line read each time
      string strLine = "";

      //record the content of each field in each line of the record
      string[] aryLine;
      //Mark the number of columns      
      int columnCount = 0;
      //indicate whether it is the first line read
      bool IsFirst = true;

      if (IsFirst == true)
      {
        //strLine = "ATTENDANCE_DATE,EMP,ATTENDANCE_DEPT,EMP_TYPE,SHITF,PLANT_CODE";
        strLine = columnName;
        aryLine = strLine.Split(',');
        IsFirst = false;
        columnCount = aryLine.Length;
        //create column
        for (int i = 0; i < columnCount; i++)
        {
          DataColumn dc = new DataColumn(aryLine[i].ToUpper());
          dt.Columns.Add(dc);
        }
      }

      //record the content of each field in each line of the record
      while ((strLine = sr.ReadLine()) != null)
      {
        aryLine = strLine.Split('\t');//tab
        DataRow dr = dt.NewRow();
        for (int j = 0; j < columnCount; j++)
        {
          dr[j] = aryLine[j].ToUpper();
        }
        dt.Rows.Add(dr);
      }

      sr.Close();
      fs.Close();
      return dt;
    }

The above is the C # implementation of TXT document to table example code, C # tutorial details, more about C # TXT document to table information please pay attention to

How to generate PDF by C #

In the previous project, we used wkhtmltopdf to render web pages to generate PDF files. This scheme has not been very stable, and the styles of different scenes are often different, so it needs to be adjusted. Today, we have studied the scheme of generating PDF directly by C #, which is relatively simple. The overall scheme is as follows:

Generate XPS file through WPF library
Convert XPS file into PDF file through pdfsharp
first, take a look at the code of generating XPS file. The code is as follows:

var fixedDoc = new FixedDocument();
var pageContent = new PageContent();
var fixedPage = new FixedPage();
 
fixedPage.Children.Add(canvas);
((IAddChild)pageContent).AddChild(fixedPage);
fixedDoc.Pages.Add(pageContent);
 
using var xpsd = new XpsDocument(@"r:\3.xps", FileAccess.ReadWrite);
var xw = XpsDocument.CreateXpsDocumentWriter(xpsd);
 
xw.Write(fixedDoc);
xpsd.Close();

Because visual in WPF can be converted to XPS file. Thanks to the powerful display ability of WPF, even rendering complex XPS files is very easy.

After having the XPS file, the next step is to convert it to PDF. Here, I use the free pdfsharp package. Because I use. Net 5, I introduce PDF PdfSharp.Xps.dotNet . core, the code is relatively simple, a line of code can be done.

PdfSharp.Xps.XpsConverter.Convert(@"r:\3.xps", @"r:\3.pdf", 0);

The scheme of generating PDF is simple and easy to use with the help of class library of WPF platform, and can realize visualization. The disadvantage is that you can’t run on Linux. If you want to realize PDF generation on Linux platform, you can also use pdfsharp directly. For details, please refer to this article: PDF generation and printing in. Net

The above is the detailed content of the method for C to generate PDF. For more information about C to generate PDF, please refer to