您的位置:首页 > 其它

excel导入导出

2015-06-06 13:33 295 查看
ExcelWriter类

using System;
using System.Collections.Generic;
using System.Xml;
using System.Text;

namespace MedicalDataManage
{
public class ExcelWriter
{
string ssns = "urn:schemas-microsoft-com:office:spreadsheet";
string xmlns = "urn:schemas-microsoft-com:office:spreadsheet";
XmlDocument _doc = new XmlDocument();
XmlNode _currentSheet = null;
XmlNode _currentRow = null;

public ExcelWriter()
{
//excel的xml模版,你需要了解xml的Attributes怎么用
StringBuilder sbody = new StringBuilder();
sbody.Append("<?xml version=\"1.0\"?>\n");
sbody.Append("<?mso-application progid=\"Excel.Sheet\"?>\n");
sbody.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\n");
sbody.Append("xmlns:o=\"urn:schemas-microsoft-com:office:office\"\n");
sbody.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\n");
sbody.Append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\n");
sbody.Append("xmlns:html=\"http://www.w3.org/TR/REC-html40\">\n");
sbody.Append("<Styles>\n");
sbody.Append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\n");
sbody.Append("<Alignment ss:Vertical=\"Center\"/>\n");
sbody.Append("<Borders/>\n");
sbody.Append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"10\"/>\n");
sbody.Append("<Interior/>\n");
sbody.Append("<NumberFormat/>\n");
sbody.Append("<Protection/>\n");
sbody.Append("</Style>\n");
sbody.Append("</Styles>\n");
sbody.Append("</Workbook>\n");
_doc.LoadXml(sbody.ToString());
}
/// <summary>
/// 增加一个工作表
/// </summary>
/// <param name="sheetName">工作表名称</param>
public void CreateSheet(string sheetName)
{
System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Worksheet", ssns);
System.Xml.XmlAttribute xa = _doc.CreateAttribute("ss", "Name", xmlns);
xa.Value = sheetName;
node.Attributes.Append(xa);
_doc.ChildNodes[2].AppendChild(node);
node.AppendChild(_doc.CreateNode(XmlNodeType.Element, "Table", xmlns));
_currentSheet = node;
}
/// <summary>
/// 增加一行
/// </summary>
public void CreateRow()
{
System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Row", xmlns);
_currentSheet.ChildNodes[0].AppendChild(node);
_currentRow = node;
}
/// <summary>
/// 增加一列
/// </summary>
/// <param name="index">索引</param>
/// <param name="width">宽度</param>
public void CreateColumn(int index, float width)
{
System.Xml.XmlNode node = _doc.CreateNode(XmlNodeType.Element, "Column", xmlns);
System.Xml.XmlAttribute xa = _doc.CreateAttribute("ss", "Index", xmlns);
xa.Value = index.ToString();
node.Attributes.Append(xa);
xa = _doc.CreateAttribute("ss", "Width", xmlns);
xa.Value = width.ToString();
node.Attributes.Append(xa);
_currentSheet.ChildNodes[0].AppendChild(node);
}
/// <summary>
/// 增加一个单元格
/// </summary>
/// <param name="value">值</param>
/// <param name="Type">类型</param>
/// <param name="Expression">公式</param>
/// <param name="rowSpan">跨行</param>
/// <param name="colSpan">跨列</param>
public void CreateCell(object value, string Type, string Expression, int rowSpan, int colSpan)
{
System.Xml.XmlAttribute xa = null;
System.Xml.XmlNode nodeCell = _doc.CreateNode(XmlNodeType.Element, "Cell", xmlns);
_currentRow.AppendChild(nodeCell);
if (!string.IsNullOrEmpty(Expression))
{
xa = _doc.CreateAttribute("ss", "Formula", xmlns);
xa.Value = "=" + Expression;
nodeCell.Attributes.Append(xa);
}
if (--colSpan > 0)
{
xa = _doc.CreateAttribute("ss", "MergeAcross", xmlns);
xa.Value = colSpan.ToString();
nodeCell.Attributes.Append(xa);
}
if (--rowSpan > 0)
{
xa = _doc.CreateAttribute("ss", "MergeDown", xmlns);
xa.Value = rowSpan.ToString();
nodeCell.Attributes.Append(xa);
}
System.Xml.XmlNode nodeData = _doc.CreateNode(XmlNodeType.Element, "Data", xmlns);
xa = _doc.CreateAttribute("ss", "Type", xmlns);
xa.Value = Type;
nodeData.Attributes.Append(xa);
nodeData.InnerText = value.ToString();
nodeCell.AppendChild(nodeData);
}
/// <summary>
/// 增加一个数字单元格
/// </summary>
/// <param name="value"></param>
public void CreateCellNumber(double value)
{
CreateCell(value, "Number", null, 1, 1);
}
/// <summary>
/// 增加一个字符串单元格
/// </summary>
/// <param name="value"></param>
public void CreateCellString(string value)
{
CreateCell(value, "String", null, 1, 1);
}
/// <summary>
/// 保存
/// </summary>
/// <param name="strFile"></param>
public void Save(string strFile)
{
_doc.Save(strFile);
}

}
}

ExcelOperator类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace MedicalDataManage
{
class ExcelOperator
{
//读取Excel
public static DataSet importExcelToDataSet(string FilePath)
{
string strConn;
strConn = " Provider = Microsoft.Jet.OLEDB.4.0;" + "Data Source = " + FilePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT*FROM[Sheet1$]", strConn);
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet);
}
catch (Exception ex)
{
throw new Exception("该Excel文件的工作表的名字不正确," + ex.Message);
}
return myDataSet;
}

// 把DataGridView导出到Excel
public static bool SaveDataTableToExcel(DataGridView gridview, string filePath)
{
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
app.Visible = false;
Workbook wBook = app.Workbooks.Add(1);
Worksheet wSheet = (Worksheet)wBook.ActiveSheet;
int size = gridview.ColumnCount;

////导英文字段
//for (int i = 0; i < size; i++)
//{
// wSheet.Cells[1, 1 + i] = gridview.Columns[i].DataPropertyName.ToString();
//}
////隐藏英文字段
//wSheet.Rows[1].Hidden = true;
////导中文
//for (int i = 0; i < size; i++)
//{
// wSheet.Cells[2, 1 + i] = gridview.Columns[i].HeaderText.ToString();
//}
if (gridview.RowCount > 0)
{
int row = 0;
row = gridview.RowCount;
int col = gridview.ColumnCount;
for (int i = -1; i < row; i++)
{
for (int j = 0; j < col; j++)
{
//导英文字段
if (i == -1)
{
//导中文
wSheet.Cells[1, 1 + j] = gridview.Columns[j].HeaderText.ToString();
}
else
{
string str = "";
if (gridview.Rows[i].Cells[j].FormattedValue != null)
{
str = gridview.Rows[i].Cells[j].FormattedValue.ToString();
Range rang = wSheet.Cells[i + 2, j + 1] as Range;
rang.NumberFormat = "@";
wSheet.Cells[i + 2, j + 1] = str;
}
}
}
}
////隐藏英文字段
// wSheet.Rows[1] = true;
}
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
app.ActiveWorkbook.SaveCopyAs(filePath);
app.Quit();
ExcelOperator.Kill(app);
app = null;
return true;
}
catch (Exception err)
{
app.Quit();
ExcelOperator.Kill(app);
app = null;
throw new Exception("导出Excel出错!错误原因:" + err.Message);
}

}

// 关闭进程
[DllImport("User32.dll", CharSet = CharSet.Auto)]
public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);
public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
{
IntPtr t = new IntPtr(excel.Hwnd);
int k = 0;
GetWindowThreadProcessId(t, out k);
System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);
p.Kill();
}
}
}

用法:

导出:

//导出
void ExportBtn_Click(object sender, EventArgs e)
{

Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
try
{
if (this.dataGridViewX1.Rows.Count == 0)
{
MessageBox.Show("窗口没有显示数据,请选择时间段,查询所要导出的数据是否存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
string name = "疾病发病报告数据.xls";
FolderBrowserDialog fbdFolder = new FolderBrowserDialog();
string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//ExcelOperator.SaveDataTableToExcel(this.dataGridViewX1, fbdFolder.SelectedPath + '\\' + name);
ExcelWriter excel = new ExcelWriter();
int rows = this.dataGridViewX1.RowCount;
int cols = this.dataGridViewX1.ColumnCount;
excel.CreateSheet("Sheet1");//sheetName
excel.CreateColumn(cols, 100);
excel.CreateRow();
for (int nI = 0; nI < cols; nI++)
{
excel.CreateCellString(this.dataGridViewX1.Columns[nI].HeaderText.ToString());
}

for (int nI = 0; nI < rows; nI++)
{
excel.CreateRow();
for (int nJ = 0; nJ < cols; nJ++)
{
excel.CreateCellString(this.dataGridViewX1.Rows[nI].Cells[nJ].FormattedValue.ToString());
}
}
excel.Save("c:\\tmp1.xls");
SaveFileDialog savefile = new SaveFileDialog();
savefile.FileName = fbdFolder.SelectedPath + '\\' + name;
savefile.Filter = "Excel文件|*.xls";
if (savefile.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Workbook workbook = null;
workbook = app.Workbooks.Open("c:\\tmp1.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.SaveCopyAs(savefile.FileName);
app.Quit();
}
}
catch (Exception ex)
{
app.Quit();
ExcelOperator.Kill(app);
app = null;
throw ex;
}
}

导入:

DataTable dt = new DataTable();
dt = ExcelOperator.importExcelToDataSet(strPath).Tables[0];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: