繁体   English   中英

如何使用C#以不同的颜色,大小,字体,粗体和斜体格式以excel或csv格式写入数据

[英]How to write data in excel or csv with different color, size , Font , Bold and Italic format using c#

我正在用csv写一些报告...因此,为了获得最佳可见性,我必须在将数据写入csv时以粗体样式写一些数据,并以不同的颜色写一些数据。我正在使用以下代码在csv中写..

        FileInfo outtxt = new FileInfo(filename);
        //  StreamWriter logline = outtxt.AppendText();
        // initialiseStream();
        StreamWriter logline = new StreamWriter(fs);
        if (f == 0)
        {
            logline.WriteLine("sometext");             
        }

那么我们如何格式化它。

紧急与否:

一个.csv(逗号分隔值)是piure文本文件,它包含字段分隔,;

这些文件中不能包含任何格式。

正如其他人指出的那样,.csv只是一个简单的文本文件,但是您可以使用nuget中提供的其他库来生成.xlsx文件。

我认为Epplus是一个非常易于使用的示例。

如果安装此软件包,则以下内容将为您提供示例,供您入门使用:

using OfficeOpenXml;
using OfficeOpenXml.Style;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet ws = package.Workbook.Worksheets.Add("MySheet");

                ws.Cells["A1"].Value = "Some Bold Text";
                ws.Cells["A1"].Style.Font.Bold = true;
                ws.Cells["A2"].Value = "Some blue text";
                ws.Cells["A2"].Style.Font.Color.SetColor(Color.Blue);
                ws.Cells["A3"].Value = "Some Large Text";
                ws.Cells["A3"].Style.Font.Size = 22;

                ws.Cells["A3"].Style.Border.BorderAround(ExcelBorderStyle.Thin, Color.Red);

                ws.Row(3).Height = 23;
                ws.Column(1).AutoFit();

                package.SaveAs(new System.IO.FileInfo(@"C:\Temp\example.xlsx"));
            }
        }
    }
}

我猜您正在谈论的是在显示.csv文件时使用excel formatting CSV只是纯文本文件,多数情况下用comma分隔。

如果要format excel,请查看Open XML,您必须创建一些styles才能以粗体和彩色显示,这有点麻烦。 如果想轻松一点,您可能想看看Closed XML库。 这项工作为您完成了所有艰苦的工作,您只需调用几种方法即可完成工作。

您可以使用EasyXLS Excel库编写Excel或CSV文件,但是CSV文件不能包含格式,因为它只是纯文本文件格式。

要编写Excel文件,请使用以下代码示例:

ExcelDocument workbook = new ExcelDocument(1);
ExcelTable tableData = ((ExcelWorksheet)workbook.easy_getSheetAt(0)).easy_getExcelTable();
tableData.easy_getCell(0,0).setValue("sometext");
workbook.easy_WriteXLSFile(filename);

要格式化单元格,请使用以下示例代码:

ExcelStyle xlsStyle = new ExcelStyle();
xlsStyle.setBold(true);
xlsStyle.setForeground(Color.DarkGray);
tableData.easy_getCell(0,0).setStyle(xlsStyle);

有关格式化的更多详细信息,请检查此链接:
http://www.easyxls.com/manual/basics/format-excel-cells.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM