首先说一下需求,用户需要将一个报表的数据导出到指定的excel模板,再将这个excel模板发给客户,客户填写信息后,用户再使用该界面进行导入反写。主要功能为查询、导出、导入与保存。
(1)查询功能,这个就是从数据库中查询数据再显示到gridControl1上,就不贴代码了。
(2)导出功能,C#操作excel有很多方法,例如 Microsoft.Office.Interop.Excel 、Aspose.cells、NPOI等,我选的是引用 Microsoft.Office.Interop.Excel。注意:这个组件的索引是从1开始的!
/// <summary>
/// 导出数据至excel模板(使用Microsoft.Office.Interop.Excel组件的方式)
/// </summary>
public void ExportExcel(DataTable DT)
{
try
{
//需要添加 Microsoft.Office.Interop.Excel引用
Microsoft.Office.Interop.Excel.Application app = new
Microsoft.Office.Interop.Excel.Application();
if (app == null)//服务器上缺少Excel组件,需要安装Office软件
{
return;
}
app.Visible = false;
app.UserControl = true;
//添加模板至项目启动的debug文件夹中
string strTempPath = Application.StartupPath + @"\OfficeTemplate\模版.xls";
Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加载模板
Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
Microsoft.Office.Interop.Excel._Worksheet worksheet =
(Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一个工作薄。
if (worksheet == null)//工作薄中没有工作表
{
return;
}
//1、获取数据
int rowCount = DT.Rows.Count;
if (rowCount < 1)//没有取到数据
{
return;
}
//表头信息
worksheet.Cells[5, 3] = DT.Rows[0]["日期"].ToString();
worksheet.Cells[5, 10] = DT.Rows[0]["名称"].ToString();
//此项目需要先插入需要的行 再进行赋值
object MisValue = Type.Missing;
for (int i = 1; i <= rowCount; i++)
{
//从第八行开始新增 插入一行
Microsoft.Office.Interop.Excel.Range xlsRows =
(Microsoft.Office.Interop.Excel.Range)worksheet.Rows[9, MisValue];
xlsRows.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, MisValue);
}
//2、写入数据,Excel索引从1开始
for (int i = 1; i <= rowCount; i++)
{
int row_ = 7 + i; //Excel模板上表头占了1行
int dt_row = i - 1; //dataTable的行是从0开始的
worksheet.Cells[row_, 1] = DT.Rows[dt_row]["列名1"].ToString();
worksheet.Cells[row_, 2] = DT.Rows[dt_row]["列名2"].ToString();
worksheet.Cells[row_, 3] = DT.Rows[dt_row]["列名3"].ToString();
worksheet.Cells[row_, 4] = DT.Rows[dt_row]["列名4"].ToString();
/* 此为注释内容无需注意
string strNum = DT.Rows[dt_row]["数量"].ToString() == "" ? "0" :
DT.Rows[dt_row]["数量"].ToString();
if (strNum.Contains("."))
{//字符串为浮点数
strNum = strNum.TrimEnd('0').TrimEnd('.');//1.00000
}
amount = amount + Convert.ToInt32(strNum);*/
}
//设置导出文件路径
//string dir = System.Environment.CurrentDirectory;//当前工作目录完全限定
string dir = System.Environment.SystemDirectory;//系统目录的
string filePath = FileDialogHelper.SaveExcel("需要填写的文件名", dir);
if (!string.IsNullOrEmpty(filePath))
{
try
{
//保存生成的Excel文件
workbook.SaveAs(filePath, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Msg.ShowInformation("保存成功");
workbook.Close();
}
catch (Exception ex)
{
Msg.ShowException(ex);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
//保存excel的类
public class FileDialogHelper
{
public static string SaveExcel(string file, string path)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = path;
// saveFileDialog.Filter = "excel2003|*.xls|excel2007|*.xlsx";
saveFileDialog.Filter = "excel2007|*.xls|excel2003|*.xlsx";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.FileName = file;//文件名赋值
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
return saveFileDialog.FileName;
}
return "";
}
}
(3)导入功能,我选择引用Aspose.cells来导入数据。注意:这个组件的索引是从0开始的!
private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string _filePath = openFileDialog1.FileName;
if (_filePath != "")
{
using (FileStream fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
{
DataTable dt = Table();
Workbook wk = new Workbook();//工作簿
wk.Open(fs); //打开excel文档
Worksheet worksheet = wk.Worksheets[0];//工作表
Cells cells = worksheet.Cells;//获取worksheet所有单元格
//判断excel导入格式
if (!cells[4, 1].StringValue.Contains("日期"))
{
MessageBox.Show("导入的文档格式不对,请选择正确格式的文档导入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//循环遍历所有单元格信息
for (int i = 7; i <= cells.Rows.Count; i++)
{
if (string.IsNullOrEmpty(cells[i, 0].StringValue.Trim()))
{
break;
}
DataRow dr = dt.NewRow();
dr["表头1"] = cells[4, 2].StringValue.Trim();
dr["表头2"] = cells[4, 5].StringValue.Trim();
dr["表头3"] = cells[4, 7].StringValue.Trim();
dr["表头4"] = cells[4, 9].StringValue.Trim();
dr["列名1"] = cells[i, 0].StringValue.Trim();
dr["列名2"] = cells[i, 1].StringValue.Trim();
dr["列名3"] = cells[i, 2].StringValue.Trim();
dr["列名4"] = cells[i, 3].StringValue.Trim();
dt.Rows.Add(dr);
}
gridControl1.DataSource = dt;
gridView1.BestFitColumns();
}
}
}
}
catch (Exception es)
{
MessageBox.Show(es.ToString());
}
}