Esquema de generar un informe de Excel desde DataView (C #)

Cuerpo:
Primero, debemos referirnos a un componente de un Excel, y comencé a probar en Office XP no tiene
éxito, luego el XP para matar, 2k instalado, será exitoso, por lo que aquí se comparten las
referencias de Office 2k a los componentes relacionados Para darse cuenta la función, cite la
biblioteca de objetos de Microsoft Excel 9.0 en la pestaña COM del proyecto. Después de que la adición sea exitosa, habrá tres elementos de referencia más en la referencia:
Excel, Office y VBIDE.

 

 

2. Código específico.
Sistema a usando;
a usando System.Data;
a usando Excel;
a usando System.IO;
espacio de nombres Test.ExcelCom
{
// <el Resumen>
/// en los datos de DataView en un archivo de Excel
/// Autor: Rexsp
/ // creado: 2004-4-4
/// </summary>
public class OutputExcel
{
#region private member
/// <summary>
/// DataView de datos
/// </summary>
private DataView dv = null;
/ // <resumen>
/// Título de la tabla
/// </summary>
private string title = null;
/// <summary>
/// Ruta del archivo de salida
/// </summary>
private string outFilePath = null;
// / <summary>
/// Ingrese el nombre del archivo
/// </summary>
cadena privada inputFilePath = null;
#endregion
#region atributo público
/// <summary>
/// DataView de datos
/// </summary>
public DataView DV
{
set {dv = value;}
}
/// <summary>
/// Título de la tabla
/// </summary>
Cadena pública Título
{
set {title = value;}
get {return title;}
}
/// <summary>
/// Ruta del archivo de salida
// / </summary>
cadena pública OutFilePath
{
set {outFilePath = value;}
get {return outFilePath;}
}
/// <summary>
/// Ruta del archivo de entrada
/// </summary>
cadena pública InputFilePath
{
set {inputFilePath = value;}
get {return inputFilePath;}
}
#endregion

#region constructor
public OutputExcel ()
{
}
public OutputExcel (DataView dv, string title)
{
//
// TODO: agregue la lógica del constructor aquí
//
}
#endregion
#region public método
public void CreateExcel ()
{
int rowIndex = 4; / / Coordenada inicial de la fila
int colIndex = 1; // Coordenada inicial de la columna
ApplicationClass myApp = null;
Workbook myBook = null;
Worksheet mySheet = null;
// Si el archivo no existe, copie el archivo de plantilla como Archivo de salida
// It No es posible crear un archivo a través de File.Create aquí, porque
el archivo vacío de xls // también tiene un formato fijo, que es diferente al texto. Puede haber otros
// métodos para generar Excel directamente a través del programa, puede probar
si (! File.Exists (outFilePath))
{
File.Copy (inputFilePath, outFilePath, true);
}
myApp = new ApplicationClass ();
myApp.Visible = falso;
objeto oMissiong = System.Reflection.Missing.Value;
myApp.Workbooks.Open (outFilePath, oMissiong, oMissiong, oMissiong, oMissiong,
oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong, oMissiong);
myBook = myApp.Workbooks [1];
mySheet = (Hoja de trabajo) myBook.ActiveSheet;

//
// Obtener el título
//
foreach (columna DataColumn en dv.Table.Columns)
{
colIndex ++;
mySheet.Cells [4, colIndex] = col.ColumnName;
mySheet.get_Range (mySheet.Cells [4, colIndex], mySheet . Cells [4, colIndex]). HorizontalAlignment = XlVAlign.xlVAlignCenter;
// Establecer el formato del título en la alineación central
}
//
// Obtener los datos en la tabla
//
foreach (fila DataRowView en dv)
{
rowIndex ++;
colIndex = 1;
foreach (columna DataColumn en dv.Table.Columns)
{
colIndex ++;
if (col.DataType == System.Type.GetType ("System.DateTime"))
{
mySheet.Cells [rowIndex, colIndex] = ( Convert.ToDateTime (fila [col.ColumnName] .ToString ())). ToString ("aaaa-MM-dd");
mySheet.get_Range (mySheet.Cells [rowIndex, colIndex], mySheet.Cells [rowIndex, colIndex]). HorizontalAlignment = XlVAlign.xlVAlignCenter; // Establezca el formato de campo del tipo de fecha en la alineación central
}
else
if (col.DataType = = System .Type.GetType ("System.String"))
{
mySheet.Cells [rowIndex, colIndex] = "'" + fila [col.ColumnName] .ToString ();
mySheet.get_Range (mySheet.Cells [rowIndex, colIndex ], mySheet.Cells [rowIndex, colIndex]). HorizontalAlignment = XlVAlign.xlVAlignCenter; // Establezca el formato del campo de caracteres en la alineación central
}
else
{
mySheet.Cells [rowIndex, colIndex] = row [col.ColumnName] .ToString () ;
}
}
}
//
// Cargar una fila total
//
int rowSum = rowIndex + 1;
int colSum = 2;
mySheet.Cells [rowSum, 2] = "Total";
mySheet.get_Range (mySheet.Cells [rowSum, 2], mySheet.Cells [rowSum, 2]) = XlHAlign.xlHAlignCenter the HorizontalAlignment ;.
//
// Establece el seleccionado porción El color
//
mySheet.get_Range (mySheet.Cells [rowSum, colSum], mySheet.Cells [rowSum, colIndex]). Select ();
mySheet.get_Range (mySheet.Cells [rowSum, colSum], mySheet.Cells [rowSum , colIndex]). Interior.ColorIndex = 19; // Establecer en amarillo claro, hay 56 tipos en total
//
// Obtener el título de todo el informe
//
mySheet.Cells [2,2] = title;
//
// Establecer el informe completo El formato de encabezado
//
mySheet.get_Range (mySheet.Cells [2,2], mySheet.Cells [2,2]). Font.Bold = true;
mySheet.get_Range (mySheet.Cells [2, 2], mySheet.Cells [2,2]). Font.Size = 22;
//
// Establezca el formulario del informe con el ancho más adecuado
//
mySheet.get_Range (mySheet.Cells [4,2], mySheet.Cells [rowSum, colIndex]). Select ();
mySheet.get_Range (mySheet.Cells [4,2], mySheet.Cells [rowSum, colIndex]). Columns.AutoFit ();
//
// Establezca el título de todo el informe en el centro de las columnas
//
mySheet.get_Range (mySheet.Cells [2,2], mySheet.Cells [2, colIndex]). Select ();
mySheet. get_Range (mySheet.Cells [2,2], mySheet.Cells [2, colIndex]). HorizontalAlignment = XlHAlign.xlHAlignCenterAcrossSelection;
//
// Dibuja el borde
//
mySheet.get_Range (mySheet.Cells [4,2] , mySheet. Cells [rowSum, colIndex]). Borders.LineStyle = 1;
mySheet.get_Range (mySheet.Cells [4,2], mySheet.Cells [rowSum, 2]). Borders [XlBordersIndex.xlEdgeLeft] .Weight = XlBorderWeight .xlThick; // Establecer la línea izquierda en negrita
mySheet.get_Range (mySheet.Cells [4,2], mySheet.Cells [4, colIndex]). Borders [XlBordersIndex.xlEdgeTop] .Weight = XlBorderWeight.xlThick; // Establecer el borde superior más grueso
mySheet.get_Range (mySheet.Cells [4, colIndex], mySheet.Cells [rowSum, colIndex]). Borders [XlBordersIndex.xlEdgeRight] .Weight = XlBorderWeight.xlThick; // Establezca la línea derecha para que sea más gruesa
mySheet.get_Range (mySheet.Cells [rowSum, 2] , mySheet .Cells [rowSum, colIndex]). Borders [XlBordersIndex.xlEdgeBottom] .Weight = XlBorderWeight.xlThick; // Establecer la línea inferior en negrita
myBook.Save () ;;
myBook.Close (true, outFilePath, true);
System .Runtime .InteropServices.Marshal.ReleaseComObject (mySheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (myBook);
System.Runtime.InteropServices.Marshal.ReleaseComObject (myApp);
GC.Collect ();

}
#endregion
}

}
Una nota: cuando se opera Excel, el proceso de Excel puede ocurrir está bloqueado, no puede retroceder
, la solución está en el Después de guardar y cerrar myBook (libro de trabajo), no cierre Excel en el
proceso (//myApp.Quit () ;). El resultado es siempre un Excel en el
proceso del servidor . Puede parecer que el usuario de asp_net no tiene autoridad suficiente para operar Excel y configurar Dcom. Transporta la
línea Dcomcnfg.exe, busca la aplicación Excel, configura sus propiedades, nivel de autenticación
"ninguno", la identidad de la elección "Usuario interactivo", página de seguridad, inicia y accede a ambos para
todos. Nota: Verifique si hay procesos Winword en el proceso actual, si hay uno y
no se puede completar, luego reinicie la computadora. Ejecute su código nuevamente y estará bien. De modo que después
de la situación no hubo suficiente autoridad.
3. Llame a
#region para probar Excel
QuickItemCollection qic = new QuickItemCollection ();
qic.GetAllInfo ();
DataView dv = new DataView ();
DataTable dt = new DataTable ("Excel");
dt.Columns.Add ("ID" , System.Type.GetType ("System.String"));
dt.Columns.Add ("ItemName", System.Type.GetType ("System.
int qicCount = qic.Count;
para (int i = 0; i <qicCount; i ++)
{
DataRow dr = dt.NewRow ();
dr [0] = qic [i] .ID;
dr [1] = qic [i] .ItemName;
dt.Rows.Add (dr);
}
OutputExcel ope = new OutputExcel ();
ope.DV = dt.DefaultView;
ope.Title = "测试 生成 Excel";
ope.InputFilePath = Server.MapPath ("Sample.xls");
ope.OutFilePath = Server.MapPath ("Test.xls");
ope.CreateExcel ();
#endregion

 

Supongo que te gusta

Origin blog.csdn.net/jinzhengquanqq/article/details/5878273
Recomendado
Clasificación