在格式化模板中将csv转换为xls时,为什么第一张纸未格式化?

时间:2019-04-26 17:54:51

标签: c# excel csv interop xls

构建一个读取CSV文件并将其在VS 2017中使用c#将其转换为xls的应用程序。

我正在使用CsvHelper和Microsoft.Office.Interop.Excel来完成此任务。

应用程序可以读取Windows窗体中的CSV文件,让程序设置一个模板并将所有正确单元格中的值插入该格式化的模板中,但是无论使用哪个文件创建的第一页都未格式化并插入到未格式化的excel页面中。

我尝试过:

  1. 更改“ Workbook.Sheets.Add”的参数
  2. 将工作表添加到逻辑上的位置
  3. 更改SaveAs函数中的参数
  4. 将各种索引从1更改为0,反之亦然

我是使用(Interop.Excel)命名空间的新手,并且花了很多时间阅读MS网页上的DOCS,但仍然无法解决此问题。

这是我将页面添加到工作簿的方式:

if (!backgroundWorker.CancellationPending)
                        {
                            backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                            Thread.Sleep(delay);
                            wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,Type:template);
                            Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                        }

这是我保存页面的方式:

wb.SaveAs(fileName, XlFileFormat.xlWorkbookDefault, missing, missing, true, false, XlSaveAsAccessMode.xlNoChange,
                        XlSaveConflictResolution.xlLocalSessionChanges,
                        missing, missing);
                    excel.Quit();

这里是对整个方法的引用:

namespace csvReader
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        struct DataParameter
        {
            public List<material> materialList;
            public List<material> smallMats;
            public Workbook wbData;
            public string Filename { get; set; }
            public int Delay;
        }

        DataParameter _inputParameter;
private void btnWrite_Click(object sender, EventArgs e)
        {
            if (backgroundWorker.IsBusy)
                return;
            using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Excel Workbook|*.xls" })
            {
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    _inputParameter.Filename = sfd.FileName;
                    _inputParameter.materialList = materialBindingSource2.DataSource as List<material>;
                    _inputParameter.Delay = 100;
                    progressBar.Minimum = 0;
                    progressBar.Value = 0;


                    backgroundWorker.RunWorkerAsync(_inputParameter);
                }
            }
        }
 private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            object missing = Type.Missing;
            List<material> list = ((DataParameter)e.Argument).materialList;
            List<material> cellM = ((DataParameter)e.Argument).smallMats;
            string fileName = ((DataParameter)e.Argument).Filename;
            int pageCount = 1;
            int process = list.Count;
            int setRows = 19;
            int delay = 100;

            if (list.Count > setRows)
            {
                pageCount = process / setRows;
            }
            Microsoft.Office.Interop.Excel.Application excel = new 
    Microsoft.Office.Interop.Excel.Application();
            string template = "(mytemplatefilepath)";
            Workbook wb = ((DataParameter)e.Argument).wbData;
            wb = excel.Workbooks.Add();
            excel.Visible = false;

            int index = 1;

            try
            {
                for (int i = 1; i < pageCount; i++)
                {
                    if (!backgroundWorker.CancellationPending)
                    {
                        backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                        Thread.Sleep(delay);
                        wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,Type:template);
                        Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                    }
                }

                int range = 1;
                int sheetIndex = 1;


                foreach (Worksheet w in wb.Sheets)
                {                    
                    w.Name = "Sheet" + sheetIndex++;
                    //w.Cells["L", 3] = tbSpecial.Text;
                    cellM = list.GetRange(range, 19);
                    int startCell = 7;
                    foreach (material m in cellM)
                    {
                        if (!backgroundWorker.CancellationPending)
                        {

                            backgroundWorker.ReportProgress(index++ * 100 / process);
                            Thread.Sleep(delay);
                            Microsoft.Office.Interop.Excel.Range newInput = w.get_Range("C" + startCell, "L" + startCell) as Microsoft.Office.Interop.Excel.Range;                           
                            w.Cells[startCell, 2] = m.Qty.ToString();
                            w.Cells[startCell, 3] = m.Section.ToString();
                            w.Cells[startCell, 4] = m.Length.ToString();
                            w.Cells[startCell, 5] = m.Camber.ToString();
                            w.Cells[startCell, 6] = m.Ends.ToString();
                            w.Cells[startCell, 7] = m.Grade.ToString();
                            w.Cells[startCell, 8] = m.Seq.ToString();
                            w.Cells[startCell, 9] = m.Member.ToString();
                            //w.Cells["L", 3] ="700";
                            startCell++;
                        }
                    }
                    range = range + 19;
                }
                wb.SaveAs(fileName, XlFileFormat.xlWorkbookDefault, missing, missing, true, false, XlSaveAsAccessMode.xlNoChange,
                    XlSaveConflictResolution.xlLocalSessionChanges,
                    missing, missing);
                excel.Quit();
            }
            catch (Exception ex)
            {
                backgroundWorker.CancelAsync();
                MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

这是203页的数据集中的第一页

https://imgur.com/t6dd2ip

其他202页显示为

https://imgur.com/jMuNMeb

我觉得这是我在某个地方犯的语法错误。 尽管很容易填写一个excel页面,但我还是希望程序使用我所使用的技术来完成这项工作的100%。

1 个答案:

答案 0 :(得分:1)

第一张工作表没有模板布局的原因以及如果'i = 0'炸弹的原因是默认情况下,当使用Workbooks.Add()实例化工作簿时,会添加一个新的工作表。该工作表不会被格式化,但是可以在Add方法的括号中添加一个模板,以使第一张工作表具有该格式。

string template = "C:/whereEverMyTemplateIs/template"
 wb = excel.Workbooks.Add(template);

然后只需记住已添加它,并根据需要添加了更多

for (int i = 1; i < pageCount; i++)
                {
                    if (!backgroundWorker.CancellationPending)
                    {
                        backgroundWorker.ReportProgress(index++ * 100 / pageCount);
                        Thread.Sleep(delay);
                        wb.Sheets.Add(missing,After:wb.Sheets[wb.Sheets.Count],Count:missing,
Type:template);
                        //Worksheet ws = (Worksheet)wb.Sheets[wb.Sheets.Count];
                    }
                }