【问题标题】:How to change the format of excel cells using C#如何使用 C# 更改 Excel 单元格的格式
【发布时间】:2014-11-14 00:44:18
【问题描述】:

IHi 我正在尝试将平面文件 n 读取为 excel。我可以使用数据表生成 excel 文件,但日期字段显示为 #####。我正在尝试更改单元格的格式,但无法更改。我添加了代码以供参考。请指导我,因为我需要从这个生成的表格中创建另一个表格以及公式。最有趣的是我将日期视为

在这张纸上,但如果我将此数据复制到另一张纸上,我可以看到日期字段而不是#####。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Threading.Tasks;
using System.Reflection;

namespace report
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"flat.txt";  //Flat file
            System.Data.DataTable table = ReadFile(path);
            Excel_FromDataTable(table);

        }
    private static System.Data.DataTable ReadFile(string path)
    {
        System.Data.DataTable table = new System.Data.DataTable("dataFromFile");
        DataColumn colu;
        for (int i = 0; i < 250; i++)
        {
            colu = new DataColumn("", System.Type.GetType("System.String"));
            colu.AllowDBNull = true;
            table.Columns.Add(colu);
        }
         using (StreamReader sr = new StreamReader(path))
        {
            string line;
            int rowsCount = 0;
            while ((line = sr.ReadLine()) != null)
            {
                string[] data = line.Split(new string[] { "|" },StringSplitOptions.None);// Separated by delimiter |
                table.Rows.Add();
                for (int i = 0; i < data.Length; i++)
                {
                    //if (data[i].Contains(""))
                    //if (data[i].Equals(""))
                    //    table.Rows[rowsCount][i] = "---";
                    //    data[i] = "   ";
                    if (!data[i].Equals(""))
                        table.Rows[rowsCount][i] = data[i];

                }
                rowsCount++;
            }
        }
        return table;

    }
     private static void Excel_FromDataTable(System.Data.DataTable dt)
    {

        //create an excel object and add to a work book....

        Application excel = new Application(); //check if you can use ApplicationClass
        Workbook workbook = excel.Application.Workbooks.Add(true);


        //add coulmn heading...
        int iCol = 0;
        foreach (DataColumn c in dt.Columns)
        {
            iCol++;
            excel.Cells[1, iCol] = c.ColumnName;
        }

        //add row
        int iRow = 0;
        foreach (DataRow r in dt.Rows)
        {
            iRow++;

            //add each row's cell data...
            iCol = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
            }

        }
        //Globalmissing refernce for objects we are not defining...

        object missing = System.Reflection.Missing.Value;

                    //excel.get_Range("C3", iRow).NumberFormat = "mm/dd/yyyy";
        workbook.SaveAs(@"C:/report.xls", XlFileFormat.xlXMLSpreadsheet, missing, missing, false, false, XlSaveAsAccessMode.xlExclusive, missing, missing, missing, missing, missing);
        // If wanting to make Excel visible and activate the worksheet 
        excel.Visible = true;



    }
    }
  }

   Excel file is like this





Column1 Column2 Column3
AAA #########   103
D-1 17        ########
D-2   17            ########
D-3 17  ########

【问题讨论】:

  • 您知道日期字段的列名称吗?如果知道,为什么不在您的代码中添加条件检查来格式化 DateFiled 或将该字段分配为字符串表示形式,前缀为 #mmddyyyy# 并附加 @987654323 @ 在该字段的末尾这有意义吗..?
  • 还因为您将数据解析为字符串数组.. 使用调试器在初始拆分中查看它并查看 data[8] 的位置,例如并检查 data[i] 的值和如果它不是 = 到 string.empty 或不是 null 则在 split 函数的循环中将其格式化为字符串
  • 没有列标题,所以不能使用日期字段的条件。
  • 您可以使用索引位置,因此请尝试使用它。我每天都使用 .csv / 拆分文件,所以我知道这会起作用..
  • user2897967 我发布了几个月前创建的方法的工作版本,该方法用于将任何 DataTable 转换为 CSV,还请注意我如何使用基于 string[] 位置的条件检查例如,如果fieldData[45] 有一个日期字段,那么我可以在该条件检查中检查和/或格式化我的最终日期字段分配.. 试试看,我相信你会非常满意..

标签: c# excel office-interop


【解决方案1】:

日期字段显示为######,因为日期比列长。尝试调整列的大小。

sheet.Columns.AutoFit();

也试试:

sheet.Cells[row, column] = String.Format("{0:MM/dd/yyyy}", object.DateEntered);

更新答案:

    int iRow = 0;
    foreach (DataRow r in dt.Rows)
    {
        iRow++;

        //add each row's cell data...
        iCol = 0;
        foreach (DataColumn c in dt.Columns)
        {
            iCol++;

            try
            {
                DateTime date = Convert.ToDateTime(r[c.ColumnName]);
                excel.Cells[iRow + 1, iCol] = String.Format("{0:MM/dd/yyyy", date);
            }
            catch(Exception e)
            {
                excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
            }

        }

    }

【讨论】:

  • 不一定包含负日期的日期字段也可以显示为#####,即使它们适合单元格
  • xApp.Selection.DateFormat = "MM/dd/yyyy"; DateFormat 是否适用于愤怒/选择?
  • 所以excel.Cells[iRow + 1, iCol] = r[c.ColumnName]; 在哪里r[c.ColumnName] 是。您需要检查该值是否为日期,然后像上面一样使用 String.Format,否则不要使用 String.Format。
  • 我认为他可以确定通过调试器的一个初始步骤他会看到格式我也会发布一个我写的方法,你可以将任何 DataTable 传递给它,它会转换将其转换为 .CSV 文件格式..
  • 如果我关闭该文件并在 Office 2013 中再次打开它,它会提示一条消息说文件已损坏,您是否要以任何方式打开它。如果我点击确定,那么我可以看到日期字段。
【解决方案2】:

这是我编写的一个简单方法,可以将任何 DataTable 转换为 CSV

//Declared at the class Level 
private const string tableDelim = "|";

private static DataTable GetDataTabletFromCSVFile(string csv_file_path)
{
    csvData = new DataTable(defaultTableName);
    try
    {
        using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
        {
            csvReader.SetDelimiters(new string[]
            {
                //this will be a constant declared at the class level private const string tableDelim = ",";
                tableDelim 
            });
            csvReader.HasFieldsEnclosedInQuotes = true;
            string[] colFields = csvReader.ReadFields();

            foreach (string column in colFields)
            {
                DataColumn datecolumn = new DataColumn(column);
                datecolumn.AllowDBNull = true;
                csvData.Columns.Add(datecolumn);
            }

            while (!csvReader.EndOfData)
            {
                string[] fieldData = csvReader.ReadFields();
                //Making empty value as null
                for (int i = 0; i < fieldData.Length; i++)
                {
                    if (fieldData[i] == string.Empty)
                    {
                        fieldData[i] = string.Empty; //fieldData[i] = null
                    }
                    //Skip rows that have any csv header information or blank rows in them
                    if (fieldData[0].Contains("Disclaimer") || string.IsNullOrEmpty(fieldData[0]))
                    {
                        continue;
                    }
                 }
                 csvData.Rows.Add(fieldData);
            }
        }
    }
    catch (Exception ex)
    {
      //write your own Exception Messaging here
    }
    return csvData;
}

转换 .CSV 文件并将其保存为 .XLS 格式,这是一个很好的简单参考 Stackoverflow 也是Convertting ExcelFile .CSV to .XLS Format

【讨论】:

  • 谢谢,但我们正在寻找 excel 文件
  • Excel 会打开一个 .csv 文件 btw.. 所以基本上是一样的
猜你喜欢
  • 1970-01-01
  • 2010-11-23
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 2014-04-28
  • 1970-01-01
  • 2011-01-28
  • 1970-01-01
相关资源
最近更新 更多