【问题标题】:How to programatically convert the text file to a custom made specific excel format with nice tabulated grid如何以编程方式将文本文件转换为具有漂亮表格网格的定制特定 Excel 格式
【发布时间】:2014-11-03 21:25:42
【问题描述】:

我想将我的文本文件 https://imageshack.com/i/eyRUOp6fj 转换为特定的 excel 格式,如下所示 https://imageshack.com/i/iqVnLA9vj。我该怎么做。

在文本文件中,有许多组件具有相同的位置名称。所以基本上我想将具有相同位置名称的所有组件聚集到一行,第二列中的组件总数等等。请指导我如何做到这一点。

代码片段:

 string[] lines = File.ReadAllLines(@"c:\bleh\testdata.txt");
 List<Item> allItems = new List<Item>(lines.Length);
 Dictionary<string, List<Item>> itemsByLocation = new Dictionary<string, List<Item>>   (StringComparer.OrdinalIgnoreCase);
// loop the file, start at 1 assuming headings first row
for (int i = 1; i < lines.Length; i++)
{
// nothing interesting here, just parsing the file
string[] columns = lines[i].Split(new char[] { ';', ',' });                
Item item = new Item() { 
    Designator = columns[ORDINAL_DESIGNATOR], 
    MaxPn = columns[ORDINAL_MAXPN], 
    Footprint = columns[ORDINAL_FOOTPRINT], 
    Location = columns[ORDINAL_LOCATION] };

allItems.Add(item);
List<Item> itemsForThisKey = null;
if (itemsByLocation.TryGetValue(item.Location, out itemsForThisKey) == false)
{
    // we don't already have this location in the dictionary, add it
    itemsForThisKey = new List<Item>();
    itemsByLocation.Add(item.Location, itemsForThisKey);
}
itemsForThisKey.Add(item); // add this item to the relevant grouping

}

我在项目 Error 1 The type or namespace name 'Item' could not be found (are you missing a using directive or an assembly reference?) 中遇到错误 另外,Error 7 The name 'ORDINAL_DESIGNATOR' does not exist in the current context 的错误请有帮助!!! 非常感谢。

【问题讨论】:

  • 你已经尝试过做什么?您应该向我们展示您为解决问题所做的努力。
  • @furkle 我只需要一个建议,我可以从哪里开始。谢谢

标签: c# excel visual-studio-2010 visual-studio grouping


【解决方案1】:

这是您完整代码的pastie

创建一个类来存储 excel 表的特定行。然后在循环中分配数据。

public class ExcelData
{
    public int SrNo { get; set; }
    public int Total { get; set; }
    public List<string> Designator { get; set; }
    public string Comment  { get; set; }
    public string Footprint  { get; set; }
    public string Location  { get; set; }

    public ExcelData()
    {
        Designator = new List<string>();
    }
}

并在循环中加入如下代码生成excel数据。

List<ExcelData> lstExcel = new List<ExcelData>();
ExcelData fline = null;
for (int i = 0; i < strLines.Length; i++)
{
    line = RemoveWhiteSpace(strLines[i]).Trim();
    if (line.Length == 0)
        continue;
    string[] cells = line.Replace("\"", "").Split('\t');

    if (i > 0)
    {
        if (cells[1] != LastComment)
        {
            if (fline != null)
                lstExcel.Add(fline);
            fline = new ExcelData();
            fline.SrNo++;
            fline.Footprint = cells[2].Replace(" ", "_");
            fline.Comment = cells[1].Replace(" ", "_");


            iCarousel++;
            if (iCarousel > 45)
                iCarousel = 1;
            LastComment = cells[1];
            fline.Location = String.Format("{0}:{1}", CarouselName, iCarousel);
        }

        fline.Designator.Add(cells[0].Replace(" ", "_"));                        
        fline.Total++;
    }
}
ExportInExcel(lstExcel, @"D:\myExcel.xls");

还创建一个将数据导出到 excel 文件的新函数。

注意:要使用此方法,您必须添加对 Microsoft Excel 对象库的引用。 Project-&gt;Add Reference-&gt;COM-&gt;Microsoft Excel XX.X Object Library

private void ExportInExcel(List<ExcelData> lstData, string excelPath)
{
    Microsoft.Office.Interop.Excel.Application xlApp;
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
    object misValue = System.Reflection.Missing.Value;

    xlApp = new Microsoft.Office.Interop.Excel.Application();
    xlWorkBook = xlApp.Workbooks.Add(misValue);
    xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);


    xlWorkSheet.Cells[1, 1] = "Sr No.";
    xlWorkSheet.Cells[1, 2] = "Total";
    xlWorkSheet.Cells[1, 3] = "Designator";
    xlWorkSheet.Cells[1, 4] = "Comment";
    xlWorkSheet.Cells[1, 5] = "Footprint";
    xlWorkSheet.Cells[1, 6] = "Location";

    for (int i = 0; i < lstData.Count; i++)
    {
        //i+2 : in Excel file row index is starting from 1. It's not a 0 index based collection
        xlWorkSheet.Cells[i + 2, 1] = (i + 1).ToString();
        xlWorkSheet.Cells[i + 2, 2] = lstData[i].Total.ToString();
        xlWorkSheet.Cells[i + 2, 3] = String.Join(",",lstData[i].Designator.ToArray());
        xlWorkSheet.Cells[i + 2, 4] = lstData[i].Comment;
        xlWorkSheet.Cells[i + 2, 5] = lstData[i].Footprint;
        xlWorkSheet.Cells[i + 2, 6] = lstData[i].Location;

    }

    xlWorkBook.SaveAs(excelPath, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
    xlWorkBook.Close(true, misValue, misValue);
    xlApp.Quit();

    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlApp);
}

//This function is created to release the excel class object.
private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

【讨论】:

  • 非常感谢.. 但是输出 excel 正在生成 excel 表。但是该文件只有标题列名..里面没有数据..
  • 是的,我试过.. 因为它显示 `fline.Comment = cells[1].Replace(" ", "_");` 的实例空错误
  • 是的..现在完美了..但是对齐不正确
【解决方案2】:

我认为您的问题实际上是关于如何进行分组,而不是关于如何读取文件并输出到 Excel。我猜分组选择的数据结构是字典,所以在这种情况下你的键是“位置”,你把所有匹配的项目都放在那个键上来创建一个分组。

或者,您也可以使用 linq - 下面有两种方法。

string[] lines = File.ReadAllLines(@"c:\bleh\testdata.txt");
List<Item> allItems = new List<Item>(lines.Length);
Dictionary<string, List<Item>> itemsByLocation = new Dictionary<string, List<Item>>(StringComparer.OrdinalIgnoreCase);
// loop the file, start at 1 assuming headings first row
for (int i = 1; i < lines.Length; i++)
{
    // nothing interesting here, just parsing the file
    string[] columns = lines[i].Split(new char[] { '\t' });                
    Item item = new Item() { 
        Designator = columns[ORDINAL_DESIGNATOR], 
        MaxPn = columns[ORDINAL_MAXPN], 
        Footprint = columns[ORDINAL_FOOTPRINT], 
        Location = columns[ORDINAL_LOCATION] };

    allItems.Add(item);
    List<Item> itemsForThisKey = null;
    if (itemsByLocation.TryGetValue(item.Location, out itemsForThisKey) == false)
    {
        // we don't already have this location in the dictionary, add it
        itemsForThisKey = new List<Item>();
        itemsByLocation.Add(item.Location, itemsForThisKey);
    }
    itemsForThisKey.Add(item); // add this item to the relevant grouping
}

// obligatory answer in linq
var itemsByLocationWithLinq = from singleItem in allItems
                    group singleItem by singleItem.Location into groupedItems
                    select new { Location = groupedItems.Key, Items = groupedItems.ToList() };

// now you have your groups so you can do with them as you will
foreach (var itemLocation in itemsByLocationWithLinq)            
    Console.WriteLine("Linq: {0} has {1:#,0} items", itemLocation.Location, itemLocation.Items.Count);

foreach (var itemLocation in itemsByLocation.Keys)
    Console.WriteLine("Dictionary: {0} has {1:#,0} items", itemLocation, itemsByLocation[itemLocation].Count);            

更新,该项目是行数据的简单持有者,使其更易于使用,并且 ORDINAL_DESIGNATOR 只是引用列在文本文件中的位置的常量。它们可以在适当的范围内定义如下,以使 sn-p 编译。

public class Item
{
    public string Designator { get; set; }
    public string MaxPn { get; set; }
    public string Footprint { get; set; }
    public string Location { get; set; }
}

private const int ORDINAL_DESIGNATOR = 0;
private const int ORDINAL_MAXPN = 1;
private const int ORDINAL_FOOTPRINT = 2;
private const int ORDINAL_LOCATION = 5;

【讨论】:

  • Error 1 The type or namespace name 'Item' could not be found (are you missing a using directive or an assembly reference?)
  • Error 7 The name 'ORDINAL_DESIGNATOR' does not exist in the current context
  • 这只是一个 sn-p 而不是整个程序 :) ORDINAL_DESIGNATOR 只是常量,您可以定义它们(文本文件中的列号,所以 ORDINAL_DESIGNATOR 为零,ORDINAL_MAXPN 为 1 等)。 Item 是一个简单的类来保存数据,只需定义一个具有这些属性的类。为了完整起见,我将其添加到示例中
【解决方案3】:

我不清楚你在问什么。如果您想创建 Excel 文件,我建议您使用以下选项之一:

1) 使用第三方组件编写 Excel 文件。我用过 Aspose Cells 见http://www.aspose.com/

2) 使用 C# 自动化 Microsoft 的 Excel 请参阅 http://support.microsoft.com/kb/302084

3) 使用 ADO 和 Jet 参见http://support.microsoft.com/kb/278973

【讨论】:

  • 人们还在自动化 Excel 吗?我以为这些天每个人都在使用 Open Office XML SDK :o)
  • 好吧,我承认我已经很久没有这样做了!总是有一些新奇的做事方式:)
猜你喜欢
  • 2021-02-28
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-17
  • 2021-09-20
  • 2020-12-09
相关资源
最近更新 更多