用DataGridView导入TXT文件,并导出为XLS文件

使用 DataGridView 控件,可以显示和编辑来自多种不同类型的数据源的表格数据。也可以导出.txt,.xls等格式的文件。今天我们就先介绍一下用DataGridView把导入txt文件,导出xls文件。。。
这里写图片描述

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.Office.Interop.Excel; 

之所以先把引用的命名空间单独列出来是因为楼主为了添加最后一个引用也查了许多资料。如果只是这样简单的引用最后一个命运空间,编译时出现“命名空间“Microsoft”中不存在类型或命名空间名称“Office”(是否缺少程序集引用?) ”的尴尬错误。解决方案就是添加引用和命名空间 ,添加Microsoft.Office.Interop.Excel引用,它的默认路径是C:\Program Files\Microsoft Visual Studio 9.0\Visual Studio Tools for Office\PIA\Office12\Microsoft.Office.Interop.Excel.dll。。。

接下来就是想DataGridView导入文件

private void button1_Click(object sender, EventArgs e)
{

    System.Data.DataTable dt = new System.Data.DataTable();
    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string fileName = openFileDialog1.FileName;
        //记录文件路径
        textBox1.Text = fileName; 

        //按特定编码方式将文件读入流,如果导入出现乱码可以更改这里的编码方式
        StreamReader sr = new StreamReader(fileName, Encoding.UTF8);

        string strLine = sr.ReadLine();  //读取一行

        //文件以Tab分开
        string[] ColNmae = strLine.Split('\t');
        for (int i = 0; i < ColNmae.Length; i++)
        {
            //dt.Columns.Add(ColNmae[i]);
            dt.Columns.Add();
            dt.Columns[i].ColumnName = ColNmae[i];
        }
        while (true)
        {
            strLine = sr.ReadLine();
            if (string.IsNullOrEmpty(strLine) == true)
            {
                break;
            }
            else
            {
                DataRow dr = dt.NewRow();
                string[] strList = strLine.Split('\t');

                for (int i = 0; i < strList.Length; i++)
                {
                    dr[ColNmae[i]] = strList[i];
                }
                dt.Rows.Add(dr);                     
            }
        }
        sr.Close();
        dataGridView1.DataSource = dt;
    }                        
}

出现乱码可以更改文件的编码方式

接下来就是导出为excel文件

private void button2_Click(object sender, EventArgs e)
{
    string fileName = "";   //文件路径,文件名


    saveFileDialog1.DefaultExt = "xls";//获取或设置默认文件扩展名

    if (saveFileDialog1.ShowDialog() == DialogResult.OK)
    {
        fileName = saveFileDialog1.FileName;
    }
    else
    {
        return;
    }

    Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
    if (xlApp == null)
    {
        MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
        return;
    }

    Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
    Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
    Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 

    //写入标题
    for (int i = 0; i < dataGridView1.ColumnCount; i++)
    {
        worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
    }
    //写入数值
    for (int r = 0; r < dataGridView1.Rows.Count; r++)
    {
        for (int i = 0; i < dataGridView1.ColumnCount; i++)
        {
            worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
        }
        System.Windows.Forms.Application.DoEvents();
    }
    worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
    MessageBox.Show(fileName + "的简明资料保存成功", "提示", MessageBoxButtons.OK);
    if (fileName != "")
    {
        try
        {
            workbook.Saved = true;
            workbook.SaveCopyAs(fileName);
            //fileSaved = true;
        }
        catch (Exception ex)
        {
            //fileSaved = false;
            MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
        }
    }
    xlApp.Quit();
    GC.Collect();//强行销毁 

}
posted @ 2015-07-23 18:02  阿尔伯特  阅读(2505)  评论(0编辑  收藏  举报