如何使用C#更改excel单元格的格式

时间:2014-11-13 15:59:55

标签: c# excel office-interop

IHi我试图将平面文件读取为excel。我能够使用datatable生成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  ########

2 个答案:

答案 0 :(得分: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];
            }

        }

    }

答案 1 :(得分:1)

这是我编写的一个简单的方法,可以将任何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